Switch statements

Coding with JavaScript

πŸ•‘ This lesson will take about 10 minutes

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 and JavaScript code

Next lesson: While loops