40

Every if...else if example I’ve seen includes a final else clause:

if (condition1) {
  doA();
} else if (condition2) {
  doB();
} else if (condition3) {
  doC();
} else {
  noConditionsMet();
}
alwaysDoThis();

I understand that this is basically syntactic sugar for nested if...else statements:

if (condition1) {
  doA();
} else {
  if (condition2) {
    doB();
  } else {
    if (condition3) {
      doC();
    } else {
      noConditionsMet();
    }
  }
}
alwaysDoThis();

I have never seen any examples of an if...else if that omits the last else clause. But seeing as plain if statements (without else clauses) are valid, and going by the equivalent “nested statements” above, my gut tells me that this is okay to do:

if (condition1) {
  doA();
} else if (condition2) {
  doB();
} else if (condition3) {
  doC();
}
alwaysDoThis();

Can someone point me to a resource or example that explicitly says whether or not it’s valid?

And on another level, if it is valid, would it be recommended or is it considered “bad practice”?

chharvey
  • 8,580
  • 9
  • 56
  • 95
  • Flow control exists for you to decide how to control the flow. Naturally, you can find out if it's "valid" by running the code and seeing it execute. –  Jul 22 '16 at 23:26
  • It depends on the context. You should *always* consider the `else` case, but often you don't need to handle it explicitly. However, I think the likelihood for the necessity increases with the number of cases. That conforms to your claim that it is unusual to omit the `else` clause in bigger conditional cascades. – Michael Hoff Jul 22 '16 at 23:32
  • Thanks for the edit on my answer; I learned a [new word](https://www.quora.com/Whats-the-difference-between-mutually-exclusive-events-and-collectively-exhaustive-events). – user4815162342 Aug 27 '18 at 16:16

4 Answers4

38

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.

user4815162342
  • 141,790
  • 18
  • 296
  • 355
  • no problem! I understood what you meant, but i wanted to correct the record. You were right that your conditions *should* be **mutually exclusive**, for good coding (even though it's not mandatory). But whether the final `else` clause would ever run doesn’t require your conditions to be mutually exclusive; it requires them to be **collectively exhaustive**. Look up the **MECE Principle** to learn more. – chharvey Aug 27 '18 at 16:21
  • @chharvey Yes, collectively exhaustive fits exactly what I wanted to communicate - if I'd known the term, I would have used it. Using "mutually exclusive" in its place sort of works because it's a stronger criterion so it doesn't invalidate the rest of the sentence - but collectively exhaustive covers it without being either too strict or too permissive. – user4815162342 Aug 27 '18 at 16:38
18

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
    ...
}
KevBot
  • 17,900
  • 5
  • 50
  • 68
15

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.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • That's what I figured, but I haven't seen any official documentation. Even [MDN's docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else) always have a final `else` clause. – chharvey Jul 22 '16 at 23:28
  • 2
    However, note that this does not extend to the ternary conditional operator: `a ? b : c` can never become just `a ? b` (but `a && b` has the semantics you'd expect from it). – Amadan Jul 22 '16 at 23:29
  • @chharvey: From the docs you linked: *"**statement2** Statement that is executed if condition evaluates to false and the else clause exists."* They're telling you that the `else` clause may not exist. Also the syntax shows square brackets around `[else statement2]`, which generally indicates something optional. –  Jul 22 '16 at 23:34
  • Yes I saw the square brackets and I know the `else` in a plain `if` statement is optional; I was just looking to confirm that it was *also* optional in an `if..else if` statement. – chharvey Jul 22 '16 at 23:44
  • 1
    @chharvey: JavaScript doesn't have an `else if` statement. This is also noted a couple times in the docs you linked. It only has `if (expression) statement else statement`. Because an `if` statement is a statement (obviously), you can use it after `else`, just like any other statement, like `for` or empty `;` or `switch` or any arbitrary expression statement. –  Jul 22 '16 at 23:46
  • user1106925 is simply incorrect. the block `if (expression) statement else statement` is syntactically distinct from the block `if (expression) statement else if (expression) statement` – chharvey Aug 27 '18 at 16:10
  • @chharvey no `else if` works because `if` satisfies `statement`. There's nothing special about an `if` after an `else`, any more than `for` or `while` or `return` after an `else`. – Pointy Aug 27 '18 at 16:12
  • @Pointy i disagree. i think the block `if (expression1) statement1 else if (expression2) statement2` is completely distinct from `if (expression1) statement1 else {} if (expression2) statement2`, because in the first case, `expression2` is only evaluated if `expression1` fails. whereas in the second case, `expression2` gets evaluated regardless. – chharvey Aug 27 '18 at 16:15
3

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

Community
  • 1
  • 1
Ivan
  • 34,531
  • 8
  • 55
  • 100