Jump to Categories

Switch

let fruit = 'Pineapple';

switch (fruit) {
  case 'Oranges':
    console.log('Oranges are £0.59 a pound.');
    break;
  case 'Apples':
    console.log('Apples are £0.32 a pound.');
    break;
  default:
   console.log('Sorry, we are out of ' + fruit + '.');
}

Similar to consitional if elseif statements. Benefits of using a switch may be that it makes the syntax cleaner and you can handle multiple cases easier.

switch(e) {
    case 1:
    case 2:
    case 3:
        console.log("I'm 1, 2 or 3");
        break;
    default:
        console.log("I'm anything else");

}

// Is the same as
 
if(e === 1 || e === 2 || e === 3) {
    console.log("I'm 1, 2 or 3");
} else {
   
}

See the Pen Switch by Shane Prendergast (@webknit) on CodePen.

References