javascript-condicional-switch

What is and how to use the conditional SWITCH in JavaScript

  • 4 min

The switch statement is a control structure in JavaScript that allows executing different blocks of code based on the value of a variable or expression.

It is sometimes used as a cleaner and more readable alternative to a series of nested if-else statements. Although, many people (myself included) think that instead of improving readability, it often worsens it.

If you want to learn more, check out the Introduction to Programming Course

Basic Syntax

The basic syntax of a switch statement in JavaScript is as follows:

switch (expression) {
    case value1:
        // Code to execute if expression is equal to value1
        break;
    case value2:
        // Code to execute if expression is equal to value2
        break;
    // ...
    default:
        // Code to execute if expression does not match any case
        break;
}
Copied!
  • expresion: The expression whose value is evaluated in each case.
  • case (case): Represents a specific value that is compared with the expression.
  • default: Optionally, a default block can be included, which will execute if none of the cases match the expression’s value.

The default block will execute if none of the previous cases match the expression’s value. It is optional, but it’s most common to have it.

Basic Example

Let’s see an example of how switch is used:

let number = 2;

switch (number) {
    case 1:
        console.log("One");
        break;
    case 2:
        console.log("Two");
        break;
    case 3:
        console.log("Three");
        break;
    default:
        console.log("Invalid number");
        break;
}
Copied!

In this case, depending on the value of numero:

  • 1, 2, and 3 will print the corresponding number on the screen.
  • Any other number will show “Número no válido”.

Fall-Through Between Cases

Fall-Through is the possibility of “falling” from one case to another and executing multiple code statements. Unlike other languages (like C++), “fall-through” in JavaScript is intentionally limited.

To be able to “fall” from one case to another, it is mandatory that the case from which we are falling has no statements.

Let’s see an example:

let fruit = "apple";
let color;

switch (fruit) {
  case "apple":
  case "pear":
  case "kiwi":
    color = "green";
    break;
  case "banana":
  case "lemon":
    color = "yellow";
    break;
  case "strawberry":
  case "raspberry":
  case "cherry":
    color = "red";
    break;
  default:
    color = "unknown";
}

console.log("The fruit " + fruit + " is " + color);

Copied!

In this example, switch is used to assign a color based on the given fruit. Several fruits are grouped under the same colors.

Practical Examples

These examples are intended to show how to use the Switch statement. It does not mean it is the best way to solve the problem they address. Usually, there are better alternatives.