The switch keyword

  • else...if statements are a great way to have multiple conditions but if number of conditions is very high than else...if would become hectic.

  • So here comes the switch keyword which makes it easily readable and writable.

  • The break keyword tells the computer to exit the block and not run any more code or check any other cases inside the codeblock.

Example:

let groceryItem = 'papaya';
 
switch (groceryItem) {
  case 'tomato':
    console.log('Tomatoes are $0.49');
    break;
  case 'lime':
    console.log('Limes are $1.49');
    break;
  case 'papaya':
    console.log('Papayas are $1.29');
    break;
  default:
    console.log('Invalid item');
    break;
}

// Output: Papayas are $1.29

Example:

let athleteFinalPosition = 'first place';

switch (athleteFinalPosition) {
  case 'first place':
  console.log('You get the gold medal!');
  break;
  case 'second place':
  console.log('You get the silver medal!');
  break;
  case 'third place':
  console.log('You get the bronze medal!');
  break;
  default :
  console.log('No medal awarded.');
  break;
}

// Output: No medal awarded.

Last updated