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.

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

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.

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:

That’s it for today.

Thank you for reading. Happy Coding!

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *