The Switch Statement

Published on: November 12, 2016

Welcome to the twenty-first Easy JavaScript tutorial, part of EasyProgramming.net. In the last tutorial, we looked at the if...else statement. In this tutorial, we will take a look another conditional statement called the Switch Statement. 

The switch statement works very similar to the if...else statement, in that it looks at some data and a specific piece of code is triggered based on whatever condition that's met. The switch statement may be easier for some of you in certain cases so it's extremely useful to know.

I would also recommend that you check out my Switch Statement tutorial in C++ to get additional practice on the statement. The syntax is absolutely the same between C++ and JavaScript. 

Let's look at the Syntax of a switch statement:


  switch(item to analyze){
    case "condition1":
      execute this code;
      break;
    case "condition2":
      execute this code;
      break;
    case "condition3":
    case "condition4":
      execute this code;
      break;
    default: 
      execute this code if all other cases do not match;
      break;
  }
  

To fork the fiddle and follow along: https://jsfiddle.net/easyjs/6xeatnvy/

Remember to checkout the Resources section below for associated downloadable content, JSFiddle links, and other resources. Watch the video and follow along!

Resources:



Comments: