In this post, we will be learning about JavaScript switch statements.
A Switch statement takes a variable, checks its value, and then depending on the value executes the code starting from a different point.
The Javascript Switch Statement
Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
JavaScript Code
switch (x) {
case 0:
y="a";
break;
case 1:
y = "b";
break;
case 2:
y = "c";
break;
default:
y = "d";
break;
}
Important Note
One very important thing that is easy to get wrong with the switch statement is the variable only determines the starting point of the statement.
As an observant person, you probably saw that each block of code ends with a break statement.
This is required because without a break statement, the statement will keep on executing;
the value of the variable x
only determines where the code starts executing rather than which blocks are executed. So without an intervening "break", all the code below your starting point will execute.
Default keyword
The default keyword means if the variable doesn’t match any of the values, then start executing the code from here.
Javascript Code
switch (x) {
case 0:
y="a";
break;
case 1:
y = "b";
break;
case 2:
y = "c";
break;
default:
y = "d";
break;
}
Result