A switch statement can replace multiple if checks.
It gives a more descriptive way to compare a value with multiple variants.
The syntax
The switch has one or more case blocks and an optional default.
It looks like this:
switch(x) {
case 'value1': // if (x === 'value1')
...
[break]
case 'value2': // if (x === 'value2')
...
[break]
default:
...
[break]
}
- The value of
xis checked for a strict equality to the value from the firstcase(that is,value1) then to the second (value2) and so on. - If the equality is found,
switchstarts to execute the code starting from the correspondingcase, until the nearestbreak(or until the end ofswitch). - If no case is matched then the
defaultcode is executed (if it exists).
An example
An example of switch (the executed code is highlighted):