JavaScript Switch Statement vs if/else if

Kevin Peery
The Daily Standup
Published in
1 min readSep 29, 2017

It is not always clear when one should use an if/else if statement construct versus a switch statement. The general rule is that if the code requires a many chained series of if/else if statements, then it is more efficient to use a switch statement to eliminate redundant code, as illustrated below.

A many chained if/else if statement:

if (val === 1) {
answer = “apple”;
} else if (val === 2) {
answer = “beet”;
} else {
answer = “carrot”;
}

A more efficient switch statement:

switch (val) {
case 1:
answer = “apple”;
break;
case 2:
answer = “beet”;
break;
default:
answer = “carrot”;
}

The Mozilla Development Network goes into detail about the JavaScript switch statement and how to use it.

The JavaScript if…else statement executes a particular statement if it is found to be truthy. If that condition is falsy, then another statement is executed instead.

A truthy value is one that is considered to be true when evaluated in a Boolean context. A Boolean is a logical data type that can have only the values true or false. All values are truthy unless they are specifically defined as falsy. The following are considered falsy in JavaScript:

false

0

“ ”

null

undefined

NaN

--

--