JavaScript Switch Statement

๐Ÿ“˜ What is Switch Statement?

The switch statement allows you to execute code based on the value of a variable. It is an alternative to multiple if...else if statements.

๐Ÿ’ป Syntax

switch(expression) {
  case value1:
    // code to run
    break;
  case value2:
    // code to run
    break;
  default:
    // code if no case matches
}
            

๐Ÿ”น Example

let day = 3;
switch(day) {
  case 1:
    console.log('Monday');
    break;
  case 2:
    console.log('Tuesday');
    break;
  case 3:
    console.log('Wednesday');
    break;
  default:
    console.log('Other Day');
}
            
โš ๏ธ break is necessary to prevent fall-through.

๐Ÿงช Try It Yourself

Select a number to see the day of the week: