How NOT to Code - Challenge 10
Today's challenge is in javascript. Can you find all the problems with this code? On some browsers you may see a double greater sign on the age and gpa conditionals. You can simply view that as a single greater than sign. Sorry I think this a small issue in encoding via this blog software.
<script type="text/javascript">
var gpa = 3.92;
var year = "4";
var age = 22;
var id = "123";
if (id == "123"){
if (age < 21){
if (year = 4){
if (gpa > 3.5){
if (id === 123){
alert('good student');
}else{
alert('bad student');
}
}
}
}
}
</script>
Amy wrote on 01/28/105:25 PM
The "double greater than" looks like a bitwise shift. Just sayin.Where to start?
First, there doesn't seem to be much rhyme or reason as to why some things are strings and some numbers.
if (year=4) not only sets the year to 4 (instead of the original "4"), but it will always return true. This is an easy mistake to make--I'm sure we've all made it at one time or another.
The second check on id is not only unneccessary (since we already checked it), but it will always return false, as the strict equality check will see '123' (string) as !== 123 (number).
There's also no consistency about using single or double quotes, which isn't "incorrect," but just feels 'messy' :).
Also, I didn't see the spec for this, but it seems like you might also want to alert for GPA < 3.5 and students who are under 22 and in different years (didn't respond to all possible conditions).