Switch case statement in JavaScript



In one of our earlier tutorials, we learnt about the usage of if-else statements in JavaScript. While using such conditional statements you might be needed to use multiple “if-else” statements which evaluates a certain parameter.

In such scenarios when you want to use multiple conditional statements, you can make use of “switch” statement in JavaScript.

Here is how you can make use of this statement…

Javascript Image

The general syntax to use Switch statement is as below:

switch(value){
	case "value1":
		//do something based on value1
		break;
	case "value2":
		//do something based on value 2
		break;
	default:
		//do something if none of the above values
		
}

                    

An example usage of this statement is given below:

let num=4;

switch(num){
    case 1:
        console.log("number value is 1");
        break;
    case 2:
        console.log("number value is 2");
        break;
    case 3:
        console.log("number value is 3");
        break;
    default:
        console.log("Any other value");
    
}

                    

Here, the switch statement compares the value of the variable “num” against the different values given with the “case” statements.

Each case statement is followed by the statements which should be executed if the value “num” variable matches with the value given along with respective “case” statement”.

These statements are followed by “break” statement so that the execution will break out from the switch block once the execution for that particular case gets completed. If you miss or forget the “break” statement, system will continue evaluating the subsequent “case” statements until it finds the next “break” statement. This may sometimes result in errors in the code as multiple “case” statements may get executed (unless you have intentionally removed the “break” statement for certain logic).

These statements are followed by the “default” statement followed by the set of statements to be executed when none of the cases present earlier resulted in match. This may also get executed if any of the prior case statement before the “default” statement do not have the “break” statement.

In the above example, the switch statement is evaluating a variable having a Numeric value, however this can also be equally extended to evaluate String, Boolean or any other data types.

I hope this tutorial gives you fair understanding on what is Switch statement, Why and how to use it in JavaScript.


                    
Follow Me on Social Media

Advertisement
FREE Sales CRM Software

Fully customizable CRM Software for Freelancers and Small Businesses

Signup for Free

Sign up for DigitalOcean Cloud

Get FREE $200 credits, deploy your hobby projects for Free

DigitalOcean Referral Badge
Sign up for Hostinger Cloud or VPS plans and get upto 20% Discount