JavaScript
In this tutorial we will learn about JavaScript switch conditional statement.
We use the switch
conditional statement to compare a single value with a list of values and execute a piece of code according to a match.
It is a compact version of the nested if/else statement.
Syntax
switch (value) {
case val1 :
//some code
break;
case val2 :
//some code
break;
default :
//some code
}
Alright, lets dive into the details.
We use the switch
keyword to create a switch conditional statement. Then inside it we pass a value. This value can be from a variable or result of a expression.
switch ( value ) {
}
Inside the switch we have some case
block. They have a value followed by :
colon. So, the case value is matched with the switch value. If a match is found then the code of that case block is executed.
We end the case block with the break
keyword. This takes us out of the switch.
We also have a default
which is executed if no match is found. This is optional.
In the following example case 3 code will be executed as value of variable x = 3.
var x = 3;
switch ( x ) {
case 1 :
console.log("value of x = 1");
break;
case 2 :
console.log("value of x = 2");
break;
case 3 :
console.log("value of x = 3");
break;
case 4 :
console.log("value of x = 4");
break;
default :
console.log("value of x something else");
}
Output
value of x = 3
If multiple case value have the same code then we can join them together in order to avoid repeating the same code block.
In the following example case 1 and case 2 share the same code block. Similarly, case 3 and case 4 share the same code block.
var x = 4;
switch ( x ) {
case 1 :
case 2 :
console.log("value of x <= 2");
break;
case 3 :
case 4 :
console.log("value of x >= 3 and x <= 4");
break;
default :
console.log("value of x something else");
}
Output
value of x >= 3 and x <= 4
In the above code value of x matches case 4. In the switch we can see case 3 and case 4 share the same code so, "value of x >= 3 and x <= 4" is printed in the browser console.
ADVERTISEMENT