Switch Statements in JavaScript

Switch statements are used to run different blocks of code based on different conditions. They are similar to ‘If’ statements but can be a little neater when working with many conditions. This video tutorial explains how to use switch statements in JavaScript.

Switch statements look like this:

switch(expression){
   case a:
       // code to run...
       break;
   case b:
       // code to run...
       break;
   default:
       // code to run...
}

Make sure you use the break statement at the end of each case so that the program does not continue running through the switch statement once a condition has been met. If you don’t use the break statement, the program will keep checking through all conditions even if a match has already been found. If none of the conditions are met, then you can use a default case which will run another block of code.

Watch the video below and then scroll down for the sample code:

Sample HTML code:

<html>
    <head>
        <title>Switch statements</title>
        <script src="script.js"></script>
    </head>
        
    <body>

    </body>
</html>

Sample JavaScript code (running this code would display the output “May”):

var month = 5;

switch(month){
    case 1:
        console.log("January");
        break;
    case 2:
        console.log("February");
        break;
    case 3:
        console.log("March");
        break;
    case 4:
        console.log("April");
        break;
    case 5:
        console.log("May");
        break;
    case 6:
        console.log("June");
        break;
    case 7:
        console.log("July");
        break;
    case 8:
        console.log("August");
        break;
    case 9:
        console.log("September");
        break;
    case 10:
        console.log("October");
        break;
    case 11:
        console.log("November");
        break;
    case 12:
        console.log("December");
        break;
    default:
        console.log("I'm not sure what month that is.");
}

Next tutorial: While loops

Leave a Reply