DEV Community

front_end_shifu_2022
front_end_shifu_2022

Posted on

switch statement

syntax:
switch(x) {
case 'value1': // if (x === 'value1')
...
[break]

case 'value2': // if (x === 'value2')
...
[break]

default:
...
[break]
}
Switch
Switch statement is a part of JavaScript "Conditional" Statements, which are used to perform different actions based on different conditions. Use switch to select one of many blocks of code to be executed. ... without break, if condition is true the all the next block will be executed .If no case is matched then the default code is executed (if it exists).

e.g.
let add = 1 + 3;

switch (add) {
case 3:
alert( 'small' );
break;
case 4:
alert( 'Correct' );
break;
case 5:
alert( 'big' );
break;
default:
alert( "no values" );
}

In the above example switch start to compare add to first case which is 3 .The match fails now it will the second case which is 4.well That's the correct match.so the execution start from match 4 until the nearest break.
Note:If there is no break then the execution continues with the next case without any checks.

Grouping of “case”

if we want the same code to run for case 3 and case 5:

let add = 3||5;

switch (add) {
case 4:
alert('wrong!');
break;
case 3: // (*) grouped two cases
case 5:
alert('right!');
alert("3 or 5");
break;
default:
alert('not matched" );
}

I hope you will get the idea from a example above.

Type matters:
Let’s make a point of that the equality check is always strict. The values must be of the same type to match.

e.g.

let n= prompt("Enter a number");
switch (n){
case '0':
case '1':
alert( 'One or zero' );
break;

case 2:
alert( 'not a string ');
break;

case 3:
alert( 'Nnot a string');
break;
default:
alert( 'no match');
}

For 0, 1, the first alert runs.

But for 2 and 3 the result of the prompt is a string "2" "3", which is not strictly equal === to the number 2 or 3.So we’ve got a dead code in case in both Thus default variant will execute.

Top comments (0)