JavaScript has no Else If


Surprised? Read on.

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?

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…

References

  1. MDN article
  2. ES5 spec

Related

  1. Why JavaScript ‘seems’ to get addition wrong
  2. Three Important JavaScript Concepts
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s