Switch is a statement in javascript that's used to control the data flow in programs. With other words to be able to decide what should happen from different cases or actions. Basically the same way one does with if and else, which most people probably are familiar with by now. They work in similar ways but have different syntax. With switch you type the condition once, which can be of any value, and then set up cases it should compare against. If there's a match the code inside that block will run, and if there's a break statement afterwards the switch is then finished.

At first sight switch can look a little hard to understand, it has a weird syntax with new words like case, break and default. But it's actually pretty simple and doesn't take very long to learn.

An example of switch in javascript

var num = 2;

switch (num) {
case: 1:
console.log('The num is 1');
break;
case: 2:
console.log('The num is 2');
break;
case: 3:
console.log('The num is 3');
break;
}

In the javascript example above switch is used to check if the variable num (which has the value 2) is matched against any of its cases. The first case is 1 which is not equals to 2 so that fails. The next case is 2, and as hopefully everyone knows 2 equals 2 so it's a match. The console.log function will run logging out that "The num is 2" and then the break statement below finishes it. If there's no break the switch will continue on checking the rest of its cases, which is called "switch fall through".

The default statement in switch

var city = 'Stockholm';

switch (city) {
case: 'Gothenburg':
console.log('The city is Gothenburg');
break;
case: 'New York':
console.log('The city is New York');
break;
default:
console.log('The city is Stockholm');
}

Default is pretty much the same as else in if statements. It's optional and is what should be run if none of the cases in the switch results in true. Note that no break is necessary at default, since it's always the last case and afterwards the switch is finished.

Try it yourself

Below is an example of a "dice" in javascript that results in a random number from 1 to 6. The value is stored in the variable dice.

var dice = Math.floor(Math.random() * 6) + 1;

switch (dice) {
// Add cases here from 1-6
}

  1. Finish the switch so it has a case for all numbers 1-6, logging out what the number was.
  2. Put it all inside a loop, and run it 10 times.