Do I need a last `else` clause in an `if...else if` statement? [duplicate] Do I need a last `else` clause in an `if...else if` statement? [duplicate] javascript javascript

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


The ending else is not mandatory. 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 guaranteed to be 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.


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    ...}