If you find yourself using an if
condition and having too many else if
parts, you could consider changing the if
to a switch
:
var a = '1', result = ''; switch (a) { case 1: result = 'Number 1'; break; case '1': result = 'String 1'; break; default: result = 'I don\'t know'; break; }
The result after executing this is "String 1"
. Let's see what the parts of a switch are:
The
switch
statement.An expression in parentheses. The expression most often contains a variable, but can be anything that returns a value.
A number of
case
blocks enclosed in curly brackets.Each
case
statement is followed by an expression. The result of the expression is compared to the expression found after theswitch
statement. If the result of the comparison istrue
, the code that follows the colon after the case is executed.There is an optional
break
statement to signal the end of thecase
block. If thisbreak
statement is reached, theswitch
is all done. Otherwise, if thebreak
is missing, the program...