Do I need a last `else` clause in an `if...else if` statement?

The ending else is not mandatory as far as JavaScript is concerned. As for whether it is needed, it depends on what you want to achieve.

The trailing else clause will execute when none of the specified conditions is true. If the conditions are collectively exhaustive, then an else clause is entirely superfluous, except possibly to contain an assertion that catches the "impossible" condition. In your case, whether you need an else clause depends on whether you want specific code to run if and only if neither of condition1, condition2, and condition3 are true.

else can be omitted for any if statement, there is nothing special in the last if of an if/else if chain. This is documented in any JavaScript grammar, e.g. in the specification.


You never need an else clause. (It's hard to offer examples of something that is not necessary, so I'll leave it at that.)

edit as a comment notes, square brackets in language syntax notation usually indicate that something is optional.


No need for a else block, they are not if else statement but if statements. Consider else, elseif as an extension.

Here's a link to a sitepoint thread : click this. And a similar thread on stackoverflow : click here


It is 100% valid. No, it is not bad practice. If you don't need it, don't write it.

Take the following for example:

function doStuff(data) {
    if (data.something) {
        // go format the data in some way
    }
    else if (data.somethingElse) {
        // go format the data in some other way
    }
    // must be formatted correctly, don't do anything else
    ...
}