3 ways to write conditions in Javascript

May 12, 2019

We all know if...else smells, but how to refactor them into something less smelly?

First thing first, I'm excluding ternary operator because it is simply a shorthand of conditionals --- under the hood, it's still the same thing.

If...else

Let's look at one use case of "if" statement. Assume we have a click event listener bind to the document, and clicking on each name would display a related lyric.

Intuitively, you could write the function like this:

const name = document.querySelector("#name");

document.addEventListener(
"click",
event => {
if (event.target.id.match("sally")) {
name.innerText = "Sally can't dance no more.";
}
if (event.target.id.match("jude")) {
name.innerText = "Hey Jude, don't make me cry";
}
if (event.target.id.match("layla")) {
name.innerText = "Layla, you've got me on my knees.";
}
if (event.target.id.match("lola")) {
name.innerText = "Oh my Lola, lo lo lo lo Lola";
}
if (event.target.id.match("polly")) {
name.innerText = "Polly wants a cracker.";
}
},
false
);

There are a couple issues with this approach: 1. it's quite slow. For every click on the document, each if statement is evaluated. 2. It's not absolutely exclusive of each other.

Switch Statement

Let's try to iterate on this more. Another approach you can take is to make a switch statement:

document.addEventListener("click", event => {
let element = event.target;
switch (true) {
case element.id === "sally":
name.innerText = "Sally can't dance no more.";
break;
case element.id === "jude":
name.innerText = "Hey Jude, don't make me cry";
break;
case element.id === "layla":
name.innerText = "Layla, you've got me on my knees.";
break;
case element.id === "lola":
name.innerText = "Oh my Lola, lo lo lo lo Lola";
break;
default:
name.innerText = "Polly wants a cracker.";
}
});

Switch statement is a bit faster than if.

Object Literal

function dispatch(event) {
var map = {
sally: function() {
name.innerText = "Sally can't dance no more.";
},
jude: function() {
name.innerText = "Hey Jude, don't make me cry";
},
layla: function() {
name.innerText = "Layla, you've got me on my knees.";
},
lola: function() {
name.innerText = "Oh my Lola, lo lo lo lo Lola";
},
polly: function() {
name.innerText = "Polly wants a cracker.";
}
};

var func = map[event.target.id];
if (func) func(event);
}
document.addEventListener(
"click",
event => {
dispatch(event);
},
false
);

You can see the example in codepen here.

See the Pen 3 ways to refactor if statements by Amie Chen (@amiechen) on CodePen.