The following code might be very familiar to you, in fact I write this too a lot.
if (a > b) {
return 1;
} else if (b > a) {
return -1;
} else {
return 0
}
However what JavaScript actually parses is shown below
if (a > b) {
return 1;
} else {
if (b > a) {
return -1;
} else {
return 0
}
}
Same end result but closer to the underlying language semantics.
Why does JavaScript not have if/else?
JavaScript allows if/else conditionals to omit the wrapping braces – some actually argue this is a neater style due to its terseness.
A contrived example is shown below.
if (a > b)
return 1;
else
return -1;
Consequently it follows that the else in the else if line is actually omitting its {} wrappers.
So whenever you write else if, you are technically not following the rule of always using braces. Not saying it is a bad thing though…
3 thoughts on “JavaScript has no Else If”