JavaScript: Working With Conditionals
Should you use if-else, switch, or a lookup table?
One of the things that differentiates a programming language (like JavaScript) from a markup language (like HTML) is the ability to handle control flow. Control flow is what makes a language smart, and it’s the process of directing which part of your code should run and at which time. You might not even realize that you’re actually using control flow — and conditionals — every single day! Is it raining out? If true
, bring an umbrella. Are you tired? If true
, go to bed. If false
, go ahead and start the next episode of Bridgerton.
Conditional statements are one of the ways that JavaScript manages control flow, and there are three big players in that game:
if-else
statements;switch
statements;lookup tables
.
How do you decide which is best suited to your task? There’s no hard-and-fast rule, so I’ve broken down some of the differences between them so you can see why you might choose one over the others.
The if-else statement
The syntax of an if-else
statement looks like this:
let dinner = 'pizza';
let price;if (dinner === 'hamburger') {
price = 6.99;
} else if (dinner === 'noodles') {
price = 9.99;
} else if (dinner === 'pizza') {
price = 12.99;
} else {
console.log('What would you like for dinner?');
}
The condition (the part that’s in the brackets) is checked at each level. If it evaluates as true
, then the code in the block will run; if it doesn’t evaluate as true
, the browser moves on and checks the next condition. That sequence repeats, and if none of the conditions are true
, then the browser just moves on. (One thing to note: you can opt to end the statement with a singleelse
that catches all the scenarios that don’t fit into the above conditions. If none of the conditions evaluate as true
, then the condition-less else
block will run. If you don’t want a catch-all, you can leave it off.)
The if-else
statement really shines when it’s used to navigate a relatively small number of choices, or if you’re evaluating ranges instead of fixed values. You can have as many chains of if
and else
as you like, and you can nest them, but the more layers you have the tougher it is to parse the code as a human, and the longer it will take the browser to process them.
What to do if your if-else
statements get unwieldy? Enter: the switch
statement!
The switch statement
The generally accepted use case for a switch
statement is when your if-else
becomes unmanageable or difficult to read. Not very specific, I know, but I promise after you’ve written a couple of conditionals you’ll know when it happens.
This is what a switch
statement looks like:
let dinner = 'pizza';
let price;switch (dinner) {
case 'hamburger':
price = 6.99;
break;
case 'noodles':
price = 9.99;
break;
case 'pizza':
price = 12.99;
break;
default:
console.log('What would you like for dinner?');
}
Right away you can see that even though the break
keyword adds an extra line for every case, it’s really easy to read. The expression in the brackets after the word switch
is what is being evaluated. When the browser finds a case
that matches the value of the expression, then the block of code for that case
will execute.
It’s very important to include the break
keyword at the end of each case to tell the browser that you’re done. If you forget to tell the browser to break
, it will run not only the matching case but every case that comes after it! The optional default
keyword is similar to the optional lone else
that can be used with the if-else
— it provides a fallback if none of the conditions are met.
Now that you’ve met if-else
and switch
, there’s actually one other way to approach conditionals, and it’s called a lookup table
.
The lookup table
Lookup tables
don’t get a lot of love when you’re learning JavaScript. They’re not really part of the conversation about conditionals so they might not be top-of-mind when you’re thinking about control flow. But they’re quick to write, they’re easy for a human to read, and they’re good for any number of conditions.
Here’s how a lookup table
works: put your conditions in an object (remember that an array is an object, so that will also work). The browser performs a lookup on the object. Done! The lookup table
doesn’t evaluate for true
or false
, which is why it’s so fast, and that’s also why it’s not technically a conditional.
Let’s check out our dinner using a lookup table
:
let menu = {
hamburger: 6.99,
noodles: 9.99,
pizza: 12.99
}let dinner = (food) => menu[food] || 'What would you like for dinner?';dinner('pizza');
SO CLEAN! No blocks, no breaks. Just an object, a function, and some pizza.
Here’s what all the parts are doing:
- The object holds the conditions (in this case, they’re key:value pairs, but they could be single array items or they could be objects nested in an array);
- The
dinner
function takes an argument, which gets looked up as a property ofmenu
; - If the property exists in the
menu
object, then the value associated with that property is returned; if the property doesn’t exist, theor
part of the function (defined using the||
short-circuit operator) will execute. (This is serving the same purpose as the finalelse
in theif-else
, or thedefault
in theswitch
.)
A lookup table is awesome if your data consists of key:value pairs or groups of associated data (think: a shirts
array and each object has a unique style, size, colour, and fabric).
The tl;dr
- If you only have a few conditions to check, or if you’re evaluating ranges, use an
if-else
. - If you have more than a few conditions or your
if-else
is too much to handle, use aswitch
. - If you have more than half a dozen-ish conditions (clearly a vague guideline), the
lookup table
is the fastest option.
Remember that technically there’s no reason you can’t use a lookup table for two conditions or an if-else for 700 conditions, but you’ll want to consider readability and performance (as well as potential scalability, if that’s relevant).