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:
switch
statement.case
blocks enclosed in curly brackets.case
statement is followed by an expression. The result of the expression is compared to the expression found after the switch
statement. If the result of the comparison is true
, the code that follows the colon after the case is executed.break
statement to signal the end of the case
block. If this break
statement is reached, the switch
is all done. Otherwise, if the break
is missing, the program execution enters the next case
block.default
statement and followed by a block of code. The default case is executed if none of the previous cases evaluated to true
.In other words, the step-by-step procedure for executing a switch
statement is as follows:
switch
expression found in parentheses; remember it.case
and compare its value with the one from step 1.true
, execute the code in the case
block.break
statement at the end of it, exit the switch.break
or step 2 returned false
, move on to the next case
block.default
statement.Best practice tips
case
lines. You can also indent case
from the switch
, but that doesn't give you much in terms of readability. break
.break
intentionally, but that's rare. It's called a fall-through and should always be documented because it may look like an accidental omission. On the other hand, sometimes you may want to omit the whole code block following a case
and have two cases sharing the same code. This is fine, but doesn't change the rule that if there's code that follows a case
statement, this code should end with a break
. In terms of indentation, aligning the break
with the case
or with the code inside the case is a personal preference; again, being consistent is what matters.default
case. This helps you make sure you always have a meaningful result after the switch
statement, even if none of the cases matches the value being switched.13.58.150.59