JavaScript switch case statement with an example

We can find the switch case statement almost in all programming languages. The main concept is the same, but the syntax may vary in different types of programming language.

In JavaScript also, we can see the switch case statement just like many other languages.

I think this is the time to introduce you with JavaScript switch case statement with a simple example so that you will understand what is it actually even you never introduced with it before in any other language.

Before I go to give you the code example, let me tell you what a switch statement exactly do.

The switch case statement in programming languages executes a block of code depending on different cases. With this conditional statement, our code can perform different actions depending upon the conditions.

In our example, we are going to see the example of the JavaScript switch case statement.



Below is our JavaScript program which is the example of a switch statement.

var weather = "rainy";

switch(weather) {
  case "rainy":
      console.log("Stay at home");
    break;
  case "sunny":
      console.log("Go to play");
    break;
  default:
      console.log("Watch cartoon");
}

In our above javaScript program, first, we take a variable and assign a string inside the variable. After that, we have used a switch statement and pass the variable inside the switch statement parenthesis as you can see in our code.

Also, read:

Inside our switch statement, we have set different types of cases that are depending upon the value of variables. Depending on the value of our variable, a different block of code will run.

As, you can see that the first case, check if the variable has value “rainy”, then it will show “Stay at home” in the console log. Similarly, we have another case where we check if the variable is “sunny”, it will show “Go to play” in the console log.

The last one we set to default and a code block under it. This means, if no value of the variable matches with the value, it will run the default code.

We can use as many cases as we want. We have to break the execution of the switch statement if the variable matches with any one of the values using the break keyword.

Now if we run the code that we have in this example, then we will see “Stay at home” in the console log as the value of the variable we have taken is “rainy”.

I hope you have understood what is switch case statement exactly in JavaScript and how it works.

Leave a Reply

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