How can I achieve an elseif in a JavaScript condition?
You could use this syntax which is functionally equivalent:
switch (true) {
case condition1:
//e.g. if (condition1 === true)
break;
case condition2:
//e.g. elseif (condition2 === true)
break;
default:
//e.g. else
}
This works because each condition
is fully evaluated before comparison with the switch
value, so the first one that evaluates to true
will match and its branch will execute. Subsequent branches will not execute, provided you remember to use break.
Note that strict comparison is used, so a branch whose condition
is merely "truthy" will not be executed. You can cast a truthy value to true
with double negation: !!condition
.