AI Workshop: learn to build apps with AI →
Conditionals: `switch`

Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.


An if/else statement is great when you have a few options to choose.

When there are too many, however, it might be overkill. Your code will look too complex.

In this case you might want to use a switch conditional:

switch(<expression>) {
  //cases
}

Based on the result of the expression, JavaScript will trigger one specific case you define:

const a = 2
switch(a) {
  case 1:
    //handle case a is 1
    break
  case 2:
    //handle case a is 2
    break
  case 3:
    //handle case a is 3
    break
}

You must add a break statement at the bottom of each case, otherwise JavaScript will also execute the code in the next case (and sometimes this is useful, but beware of bugs).

You can provide a default special case, which is called when no case handles the result of the expression:

const a = 2
switch(a) {
  case 1:
    //handle case a is 1
    break
  case 2:
    //handle case a is 2
    break
  case 3:
    //handle case a is 3
    break
  default:
    //handle all other cases
    break
}

Lessons in this unit:

0: Introduction
1: Comparison operators
2: `if` statements
3: How to use `else`
4: ▶︎ `switch`
5: The ternary operator