DEV Community

Cover image for The JavaScript Switch Statement Explained with Examples
Hillary Nyakundi
Hillary Nyakundi

Posted on • Updated on • Originally published at sweetcode.io

The JavaScript Switch Statement Explained with Examples

Full article available on Sweetcode for free

When learning any programming language, you will come across the concept of control flow. This is when we want our program to behave differently, based on the information and values we supply to it.

One popular control flow structure is a switch statement. This will evaluate an expression and perform an action, based on the resulting value. In this article, we are going to learn how switch statements are implemented in JavaScript and how they differ from other control structures, such as if...else statements.

Let’s get right to it.

The Syntax of a Switch Statement

The basic syntax of a switch statement is like so:

switch (expression) {
  case value_1:
    statement_1;
    break;
  case value_2:
    statement_2;
    break;
  default:
    default_statement;
}
Enter fullscreen mode Exit fullscreen mode

As you can see, the switch statement receives an expression. An expression is any unit of code, that resolves to a value. For example:

  • 3 + 4
  • 'hello' + 'world'
  • a > 20
  • false

You can read more about expressions on MDN.

The switch statement will evaluate the result of the expression and either execute the matching case statement, or the default statement in the event that no case statements match.

Let's look at this using a practical example:

const name = 'lary';

switch (name) {
  case 'lary':
    alert('Hi lary!');
    break;
  case 'Hillary':
    alert('Hi Hillary!');
    break;
  default:
    alert('Howdy stranger!');
}
Enter fullscreen mode Exit fullscreen mode

Try running this code. Change the value of the name variable and notice how a different greeting is output to the screen.

Once control of a program enters a switch statement, the expression is first executed, then followed by matching the first case constant to the value of the expression result, in the case they match, the statements in that clause are executed.

In a scenario that they do not match, control of the program goes on to compare the expression’s result to the second clause, evaluating its statements when there is a match.

Once the statements of a given case clause are executed, where a break statement is used, this ends the switch case, and program control is returned to the main program. Since break statements are optional, when they are not available, the program will continue matching other case clauses that flow irrespective they matched the case without a break statement. This introduces some very unique usage for a switch statement.

In a scenario where non of the clauses match, the default clause if available is executed, calling all the statements for the default clause and then exiting the switch statement. When a default clause is not available, no statements within any of the switch cases would be executed.

Flow Diagram

Check out the complete Article on Sweetcode.

No registration is needed to access the article

Connect With me at Twitter | Insta | YouTube | LinkedIn | GitHub

Enjoy Coding ❀

Top comments (6)

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ • Edited

It's important to note that the case 'values' are expressions too. This is perfectly valid (and useful sometimes):

switch (true) {
   case a==b:
      // do something
   break;
   case a==7:
   case a>b:
      // do something else
      break;
   default:
      // do another thing
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
pengeszikra profile image
Peter Vivo

In react switch case is very common to solve reducer for useReducer

export function fooReducer (state, {type, payload}) {
 switch(type) {
   case SET_FOO: return {...state, foo: payload};
   case CLEAR_FOO: return {...state, foo: null};
   default: return state;
 }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
yasintuncel profile image
Yasin TUNCEL

I think you should use strategy pattern instead of switch case.

const days = {
    sunday: 0,
    monday: 1,
    tuesday: 2,
    wednesday: 3,
    thursday: 4,
    friday: 5,
    saturday: 6,
};

const onSunday = function (parameters) { console.log("sunday. parameters: " + parameters); }
const onMonday = function (parameters) { console.log("monday. parameters: " + parameters); }
const onTuesday = function (parameters) { console.log("tuesday. parameters: " + parameters); }
const onWednesday = function (parameters) { console.log("wednesday. parameters: " + parameters); }
const onThursday = function (parameters) { console.log("thursday. parameters: " + parameters); }
const onFriday = function (parameters) { console.log("friday. parameters: " + parameters); }
const onSaturday = function (parameters) { console.log("saturday. parameters: " + parameters); }

let dayStrategies = {};

const addDayStrategy = function (day, func) {
    dayStrategies[day] = func;
};

addDayStrategy(days.sunday, onSunday);
addDayStrategy(days.monday, onMonday);
addDayStrategy(days.tuesday, onTuesday);
addDayStrategy(days.wednesday, onWednesday);
addDayStrategy(days.thursday, onThursday);
addDayStrategy(days.friday, onFriday);
addDayStrategy(days.saturday, onSaturday);

// testing
for (let i = 0; i < 7; i++) {
    const randomDay = Math.floor(Math.random() * 10);
    try {
        dayStrategies[randomDay](Math.floor(Math.random() * 10000));
    }
    catch (err) {
        console.log("Not a day of the week.");
    }
}
Enter fullscreen mode Exit fullscreen mode

result
example image

Collapse
 
larymak profile image
Hillary Nyakundi

I will definately give it a try

Collapse
 
ribosed profile image
ribosed

Are there significant differences in the speed of execution?

Collapse
 
larymak profile image
Hillary Nyakundi

I tend to think it will depend with the program being executed