Hey, Awesome ones!
Welcome to my other blog about this JavaScript Blog Course. You can find it here↗️
In this blog, we are going to learn JavaScript Switch Statements.
What to wait?
Yeah.. let's begin🚀
The "switch" statement
A switch
statement is used to write small code and can replace multiple if & else if conditions.
Syntax:
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
The value of
expression
is checked for strict equality to the value from the firstcase
(that is,x
) then to the second (y
) and so on.If equality is found,
switch
starts to execute the code starting from the correspondingcase
, until the nearestbreak
(or until the end ofswitch
).If no case is matched then the
default
code is executed (if it exists).
Example:
let a = 2 + 3;
switch (a) {
case 3:
alert( 'Not the correct value' );
case 4:
alert( 'Move ahead!' );
case 5:
alert( 'Correct' );
default:
alert( "We can't find the number" );
}
Nesting of “case”
case
which share the same code can be grouped.
Code:
let a = 3;
switch (a) {
case 4:
alert('Right!');
break;
case 3: // (*) grouped two cases
case 5:
alert('Wrong!');
alert("Why don't you take a math class?");
break;
default:
alert('The result is strange. Really.');
}
Type Counts
let arg = prompt("Enter a value?");
switch (arg) {
case '0':
case '1':
alert( 'One or zero' );
break;
case '2':
alert( 'Two' );
break;
case 3:
alert( 'Never executes!' );
break;
default:
alert( 'An unknown value' );
}
For
0
,1
, the firstalert
runs.For
2
the secondalert
runs.But for
3
, the result of theprompt
is a string"3"
, which is not strictly equal===
to the number3
. So we’ve got a dead code incase 3
! Thedefault
variant will execute.