Bisexual Pride

There are a bunch of ways to handle conditional logic in JavaScript. These include the if statement, ternary operator, and short-circuit evaluation, among others. But I rarely see the switch statement used, and I think it’s perhaps because developers aren’t sure when to use it instead of an if statement.

The switch statement is best used when you want to check multiple values of a single expression.

Let’s look at an example.

I was recently rebuilding my Countdown Timer - Start and Pause Buttons project for the Vanilla JS Academy. I had multiple click handlers—start(), pause(), and reset()—that I was conditionally calling within a handleClick() function:

/**
* Handle click events
* @param {Event} event The Event interface
*/

function handleClick (event) {
// Start the timer
if (event.target.id === 'start') {
start();
return;
}

// Pause the timer
if (event.target.id === 'pause') {
pause();
return;
}

// Reset the timer
if (event.target.id === 'reset') {
reset();
}
}

There’s nothing wrong with this. It’s nice and readable.

However, notice that the three if statements are all checking the value of the same event.target.id property. It seems a bit superfluous to keep rewriting the same if (event.target.id === 'string') pattern over and over again.

This is the perfect place to use a switch statement instead:

/**
* Handle click events
* @param {Event} event The Event interface
*/

function handleClick (event) {
switch (event.target.id) {
case 'start':
start();
break;
case 'pause':
pause();
break;
case 'reset':
reset();
}
}

As you can see, I’m using the switch statement to check a single expression: the value of event.target.id. Then I have multiple cases to handle different values for that expression. It saves me from having to write the if (event.target.id === 'string') pattern over and over again.

For more information, I recommend reading about the switch statement in the MDN Web Docs.