I recently came across code where a switch statement seemed reversed with the answer (boolean) in the switch and the expressions in the case. The code ran fine as intended b
The syntax of switch statement is:
SwitchStatement : switch ( Expression ) CaseBlock CaseBlock : { CaseClauses(opt) } { CaseClauses(opt) DefaultClause CaseClauses(opt) } CaseClauses : CaseClause CaseClauses CaseClause CaseClause : case Expression : StatementList(opt) DefaultClause : default : StatementList(opt)
No where it says that switch expression or the case expression has to be a number, string, boolean or anything. true
is perfectly acceptable as a switch expression and y < 20
is perfectly acceptable as case expression. Keep in mind that comparison between switch expression and case expressions are made using ===
operator.
In the code you posted, the first true
case will be executed until break
is encountered or the switch block ends.