Switch Statement in Javascript: Tutorial & Examples

Updated: February 20, 2023 By: Khue Post a comment

This article is about switch statements in Javascript.

Overview

A switch statement is a control structure that allows you to perform different actions based on different conditions. It works by evaluating an expression and then executing code based on the result of that evaluation.

Here’s the basic syntax:

switch (expression) {
  case value1:
    // Code to execute if expression equals value1
    break;
  case value2:
    // Code to execute if expression equals value2
    break;
  default:
    // Code to execute if expression doesn't match any case
}

The expression is evaluated once and compared with each case value using the === operator. If the expression matches a case value, the code inside that case is executed. If there’s no match, the code inside the default block will be executed (if it exists).

The break keyword is used to exit a switch statement once a matching case is found. If you omit the break keyword, the code will “fall through” to the next case and continue executing the code inside that case as well. You can use this behavior intentionally to execute multiple cases in a row (find more details in the last section of this article).

A Complex Example

Let’s say you’re building a website that allows users to create and share custom emojis. You want to validate the emoji text that users submit and display an appropriate message depending on the validation result. Here’s an example implementation that uses a switch statement to handle different cases:

const validateEmojiText = (emojiText) => {
  switch (true) {
    case emojiText.length < 2:
      return 'Your emoji text is too short. Please enter at least 2 characters.';
    case emojiText.length > 10:
      return 'Your emoji text is too long. Please enter no more than 10 characters.';
    case /[^a-zA-Z0-9]/.test(emojiText):
      return 'Your emoji text contains invalid characters. Please use only letters and numbers.';
    case /\d{5}/.test(emojiText):
      return 'Your emoji text cannot contain five consecutive digits. Please remove them.';
    default:
      return 'Your emoji text is valid. Thank you for creating an emoji!';
  }
}

console.log(validateEmojiText('👍🏻')); 

Output:

Your emoji text contains invalid characters. Please use only letters and numbers.

Switch Statement and Object Literals

When using switch statements with object literals, we’re essentially switching between different cases based on the value of a particular property of the object literal.

Let me show you an example. Suppose we have an object called “fruit” that contains a property called “color”. We can use a switch statement to perform different actions based on the value of the “color” property:

const fruit = { color: 'red' };

switch (fruit.color) {
  case 'red':
    console.log('This fruit is likely an apple');
    break;
  case 'yellow':
    console.log('This fruit is likely a banana');
    break;
  case 'green':
    console.log('This fruit is likely a pear');
    break;
  default:
    console.log('I am not sure what fruit this is');
}

Output:

This fruit is likely an apple

Using switch statements with object literals is a great way to make your code more readable and maintainable. It’s especially useful when you have a large number of cases to handle.

Fall-Through Cases

In JavasScript, we can use the “fall-through” behavior in switch statements to execute multiple cases in a row. To achieve this, we can simply omit the break statement in a case, and the code will “fall through” to the next case, executing its code as well.

Let me show you an example:

const number = 3;

switch (number) {
  case 1:
  case 2:
    console.log('Number is either 1 or 2');
    break;
  case 3:
  case 4:
    console.log('Number is either 3 or 4');
    break;
  default:
    console.log('Number is neither 1, 2, 3, nor 4');
}

Output:

Number is either 3 or 4

In this example, we’re using the “fall-through” behavior in the first and second cases. If the value of the number is either 1 or 2, the code inside both cases will be executed. Similarly, if the value of the number is either 3 or 4, the code inside both cases will be executed.

Note that we still need to use the break statement at the end of each case to prevent the code from falling through to the next case unintentionally.

Using fall-through cases can be a powerful technique to make our code more concise and readable, but it can also lead to confusion if not used carefully. So be sure to use it only when it makes sense, and document your code properly to avoid trouble down the line.