Skip to main content

Building Blocks in JS

Switch statements in Javascript: Your Code's Traffic Controller

Let’s imagine you’re a traffic controller. Your job is to direct cars based on their colors: red cars go left, green goes right, blue goes straight, and everything else just stays put. If you had to handle this scenario with a bunch of if...else statements, it would also be a lot of repetitive work. Instead, wouldn’t it be nice to have a system that takes the car’s color and automatically directs it without you needing to write tons of conditional checks? That is where "switch" statements come into the picture.

Switch statements are like having a traffic controller that knows exactly what to do with each type of input.

Image generated using Microsoft Copilot AI

The Basics of switch

At its core, a switch statement allows you to compare a single value against multiple possible outcomes (or “cases” as we call it) and execute code based on which case matches. If none of the cases match, you can define a default action, kind of like a catch-all.

Let's look at the syntax of the switch statement. The switch statement uses a special keyword called "switch", this is similar to the other keywords of var for variable, function for functions like we saw in the previous articles.

Then we have the keyword case where the value inside the expression is evaluated against. The rest is a very easy syntax that I am sure you would be able to understand and remember, true?

switch (expression) {
  case value1:
    // code to execute if expression === value1
    break;

  case value2:
    // code to execute if expression === value2
    break;

  default:
    // code to execute if no cases match
}

The switch statement starts by evaluating the expression and then compares it to each case. When a match is found, it executes the corresponding code. The break keyword is used to exit the switch after a match is found, preventing the code from running into the next case.

Simple Example

let weather = 'sunny';

switch (weather) {
  case 'rainy':
    console.log("Don't forget your umbrella!");
    break;

  case 'sunny':
    console.log("Wear your sunglasses!");
    break;

  case 'snowy':
    console.log("Snow time");
    break;

  default:
    console.log("Let's just stay inside.");
}

In this example, the value of weather is 'sunny', so the message “Wear your sunglasses!” is displayed. If the weather value didn’t match any of the cases, the default message “Let’s just stay inside.” would be shown.

break statement

You might be wondering why we need that break statement after each case. Well, imagine you’re in a line at a buffet. You’re only supposed to take one dish and then move on, but without a sign telling you to stop after the first dish, you might just keep going down the line, grabbing everything in sight - Yeah I am a foodie!

In a switch statement, break acts like that stop sign. It tells JavaScript to stop executing further cases once it finds a match. Without it, the code will continue to execute the code for the next cases, even if they don’t match the expression. This is known as “fall-through.”

break is Missing (break failure!)

Let’s look at an example where break is intentionally left out to demonstrate fall-through:

let day = 'Tuesday';

switch (day) {
  case 'Monday':
    console.log('Start of the week.');
  case 'Tuesday':
    console.log('Second day of the week.');
  case 'Wednesday':
    console.log('Midweek already.');
  default:
    console.log('Some other day.');
}

Here, because there’s no break after the case for 'Monday', the program will continue executing all the following cases, resulting in the output:

Output:

Second day of the week.
Midweek already.
Some other day.

Even though day is 'Tuesday', all the cases from 'Tuesday' onward are executed because there are no break to stop the flow.

Grouping Cases

One of the cool things about switch is that you can group multiple cases together. This is useful when you want the same block of code to run for multiple different values.

Let’s say you’re working on a game, and you want to display a message for any level that’s either beginner or intermediate:

let level = 'intermediate';

switch (level) {
  case 'beginner':
  case 'intermediate':
    console.log('Welcome to the game!');
    break;

  case 'advanced':
    console.log('Get ready for a challenge!');
    break;

  default:
    console.log('Select a valid level.');
}

Here, both 'beginner' and 'intermediate' cases trigger the same block of code, which welcomes the player to the game. This works because the cases are stacked without a break in between, allowing the same code to run for both.

Strict Comparisons in switch

One thing to note about switch is that it uses strict equality (===) for comparisons. This means that both the value and the type must match for a case to be executed. Let’s see what I mean by this in practice:

let value = '1';

switch (value) {
  case 1:
    console.log('This is a number.');
    break;

  case '1':
    console.log('This is a string.');
    break;

  default:
    console.log('Type matters here!');
}

Even though value is '1', which looks like the number 1, it’s actually a string. Because switch checks both value and type, the case for '1' (the string) is matched, and “This is a string.” is printed. The case for 1 (the number) is not matched because the types differ.

switch vs. if...else: Which One to Use?

What we achieve with switch can also be achieved with if...elseif, then when to use which? The answer comes down to readability and organization. If you’re comparing a single value against many different possibilities, switch can be cleaner and easier to read than a long chain of if...else statements. Compare the following:

let fruit = 'apple';

if (fruit === 'banana') {
  console.log('Bananas are great!');
} else if (fruit === 'apple') {
  console.log('An apple a day...');
} else if (fruit === 'orange') {
  console.log('Oranges are packed with Vitamin C.');
} else {
  console.log('Fruit is healthy!');
}

versus

switch (fruit) {
  case 'banana':
    console.log('Bananas are great!');
    break;

  case 'apple':
    console.log('An apple a day...');
    break;

  case 'orange':
    console.log('Oranges are packed with Vitamin C.');
    break;

  default:
    console.log('Fruit is healthy!');
}

Both do the same thing, but the switch version is arguably easier to scan and understand, especially when you have multiple cases.

Let’s consider a real-world scenario where you’re developing an e-commerce website, and you want to handle different types of payment methods. Depending on the method chosen by the user, you want to execute different code:

let paymentMethod = 'credit card';

switch (paymentMethod) {
  case 'credit card':
    console.log('Processing credit card payment...');
    // logic for processing credit card
    break;

  case 'paypal':
    console.log('Redirecting to PayPal...');
    // logic for PayPal payment
    break;

  case 'bitcoin':
    console.log('Processing Bitcoin payment...');
    // logic for Bitcoin payment
    break;

  default:
    console.log('Please select a valid payment method.');
}

In this example, the switch statement cleanly handles multiple payment options, with each case providing a clear path for what happens with each payment method. If a new payment method is added in the future, it’s easy to add another case to handle it.

Converting Between switch and if...else

Sometimes, you might need to convert a switch statement into an if...else chain, or vice versa in a project you are working on. Let’s look at how you can do that - Yes, I always got you covered!

Switch statement

switch (browser) {
  case 'Edge':
    console.log("You've got the Edge!");
    break;

  case 'Chrome':
  case 'Firefox':
  case 'Safari':
  case 'Opera':
    console.log('Okay we support these browsers too');
    break;

  default:
    console.log('We hope that this page looks ok!');
}

You can rewrite this using if...else:

if (browser === 'Edge') {
  console.log("You've got the Edge!");
} else if (browser === 'Chrome' || browser === 'Firefox' || browser === 'Safari' || browser === 'Opera') {
  console.log('Okay we support these browsers too');
} else {
  console.log('We hope that this page looks ok!');
}

Both versions do the same thing, but the switch version is arguably more organized and easier to read when you’re dealing with multiple cases.

The switch statement is a powerful tool in JavaScript that can help you simplify your code and make it more readable. It’s especially useful when you have a single value that you want to compare against multiple possibilities. The next time you have multiple if...elseif statements, think switch .