Switch Case Statement in JavaScript
In this Article, you will learn how to use switch case statement in JavaScript. The switch statement is used to perform different actions based on different conditions.
JavaScript Switch…Case Statements, JavaScript Switch Statement, switch – JavaScript, JavaScript – Switch Case, The “switch” statement, Switch Case in JavaScript, How To Use the Switch Statement in JavaScript, Understanding Switch Cases in JavaScript, using a condition in switch case, Expression inside switch case statement, Switch statement multiple cases.
Checkout more articles on JavaScript
Switch Case statement gives a more efficient way to compare a value with multiple variable or expression. It’s better to use switch case than multiple if…else statements.
Syntax
1 2 3 4 5 6 7 8 9 10 | 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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 |
That’s it for today.
Thank you for reading. Happy Coding!