Enjoy 20% off all plans by following us on social media. Check out other promotions!
Quiz Questions

What is the purpose of the `switch` statement?

Topics
JAVASCRIPT
Edit on GitHub

TL;DR

The switch statement is used to execute one block of code among many based on the value of an expression. It is an alternative to using multiple if...else if statements. The switch statement evaluates an expression, matches the expression's value to a case label, and executes the associated block of code. If no case matches, the default block is executed.

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

Purpose of the switch statement

Simplifies multiple conditional checks

The switch statement provides a cleaner and more readable way to handle multiple conditional checks compared to using multiple if...else if statements. It is particularly useful when you need to compare the same expression against different values.

Syntax and structure

The basic syntax of a switch statement is as follows:

switch (expression) {
case value1:
// code to be executed if expression === value1
break;
case value2:
// code to be executed if expression === value2
break;
// more cases...
default:
// code to be executed if no case matches
}

How it works

  1. Expression evaluation: The switch statement evaluates the expression once.
  2. Case matching: It compares the result of the expression to the values of each case label.
  3. Code execution: If a match is found, the code associated with that case is executed.
  4. Break statement: The break statement is used to exit the switch block. If omitted, the next case will be executed (fall-through behavior).
  5. Default case: The default case is optional and executes if no matching case is found.

Example

Here is an example of a switch statement in action:

let fruit = 'apple';
switch (fruit) {
case 'banana':
console.log('Banana is yellow.');
break;
case 'apple':
console.log('Apple is red.');
break;
case 'grape':
console.log('Grape is purple.');
break;
default:
console.log('Unknown fruit.');
}

In this example, the output will be Apple is red. because the value of fruit matches the case 'apple'.

Fall-through behavior

If the break statement is omitted, the switch statement will continue to execute the subsequent case blocks until it encounters a break or the end of the switch block. This is known as fall-through behavior.

let day = 2;
switch (day) {
case 1:
console.log('Monday');
case 2:
console.log('Tuesday');
case 3:
console.log('Wednesday');
default:
console.log('Unknown day');
}

In this example, the output will be:

Tuesday
Wednesday
Unknown day

This happens because there are no break statements to stop the execution after the case 2 block.

Further reading

Edit on GitHub