JavaScript switch statement with example
In this article, you will learn how to use switch statement in JavaScript with example. The switch statement is used to perform different actions based on different conditions.
- How to select a random element from an array in JavaScript
- JavaScript array methods Push, Pop, Shift and Unshift
- JavaScript Spread Operator
- ES6 Rest Parameter in JavaScript
Syntax
switch(x){
case value1: // if x === value1
...
break;
case value2: // if x === value2
...
break;
default: // if x not match
...
}
Switch case statement checks each case from beginning to end until it finds a match, if finds then execute the corresponding block otherwise default code is executed.
Example
Let’s take an example where we want to return a day of week using getDay()
method. This method returns a number between 0 to 6 based on date. If it’s Sunday then it returns 0, Monday then 1, and so on.
Assume that today is Monday so getDay()
method returns 1 and based on it case 1
will be executed.
var day = new Date();
switch(day.getDay())
{
case 0:
console.log("Today is Sunday");
break;
case 1:
console.log("Today is Monday");
break;
case 2:
console.log("Today is Tuesday");
break;
case 3:
console.log("Today is Wednesday");
break;
case 4:
console.log("Today is Thursday");
break;
case 5:
console.log("Today is Friday");
break;
case 6:
console.log("Today is Saturday");
break;
default:
console.log("No Information Found");
break;
}
// Output : Today is Monday
Example of switch case for a group
Now we will explain to you how to use grouped cases in switch…case. If we want the same code to run for case 2, case 3 and case 4:
var a=3;
switch(a)
{
case 1:
console.log("Value of a is 1");
break;
case 2: // grouped three cases
case 3:
case 4:
console.log("Value of between 2 and 4");
break;
default:
console.log("Value of a not matched");
break;
}
// Output: Value of between 2 and 4
I hope you find this article helpful.
Thank you for reading. Happy Coding..!!