Switch Statement

The switch statement is used to perform different actions based on different conditions. It's often cleaner than writing many if...else if statements.

let fruit = 'apple';

switch (fruit) {
  case 'apple':
    console.log('You selected apple');
    break;
  case 'banana':
    console.log('You selected banana');
    break;
  default:
    console.log('Unknown fruit');
}

Use break to prevent fall-through behavior. If break is omitted, the next case will execute even if the previous one matches.

← PrevNext →