Monday, June 3, 2024
74
rated 0 times [  79] [ 5]  / answers: 1 / hits: 101175  / 8 Years ago, fri, july 22, 2016, 12:00:00

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”?


More From » if-statement

 Answers
19

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.


[#61277] Wednesday, July 20, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
emmaleet

Total Points: 203
Total Questions: 107
Total Answers: 98

Location: Cook Islands
Member since Thu, May 21, 2020
4 Years ago
emmaleet questions
Wed, Apr 28, 21, 00:00, 3 Years ago
Thu, Jan 7, 21, 00:00, 3 Years ago
Sat, Nov 28, 20, 00:00, 4 Years ago
Sat, Apr 18, 20, 00:00, 4 Years ago
;