article cover

How to Shorten JavaScript Conditionals with Short-Circuiting

Reed Bargerviews icon-
javascript
javascript

In this tip, you’ll learn how to reduce JavaScript conditionals to the smallest possible expression using a trick called short-circuiting.

What is short-circuiting?

As the name suggests, short-circuiting is a way we can shorten unnecessary checks in our conditionals by making use of some special tricks in the JavaScript language.

Let’s see how:

We have a simple program where we ask users of it their name and if it’s a valid name, meaning not an empty string, we’ll set that equal to their username.

Otherwise, we’ll judge them to be anonymous and give them the username “guest”. We’ll store that username as a variable.

How would we write this out as an if-else statement? Probably something like what we have here:

const response = "Reed"; // response from our user
let username;
if (response) {
username = response;
} else {
username = "guest";
}
console.log(username); // Reed

But we can shorten this even more.

This if-else statement can be written more succinctly using the ternary operator, which is ideal for conditionally setting the value of a variable.

const response = 'Reed';
const​ name = response ? response :'guest';
console.log(name); // Reed

But we can even go a step further.

|| (or) short-circuiting

In this example, you might have noticed that we writing the information check, response, twice.

Let’s assume that data is always going to be valid, which means there’s no difference between the information we’re checking and the information we want. If it’s truthy, we’re going to use it.

Before updating the code, let’s think about how logical operators, such as the or || operator, work.

The or operator, symbolized as ||, will return true if any of the possible values are true. We use it if the first value (called operand, in a conditional) or the second could evaluate to true.

Now here’s where it gets interesting—

Since in JavaScript we can use non-boolean values in our conditionals which are then coerced to true or false, if we use a truthy value in our || condition, it returns that truthy value and not the value true.

Let’s see this in action. If we have a valid name, which is a string and not a falsy value, it will be returned and put in username.

const username = "Reed" || "guest";
console.log(username); // 'Reed'

Now you have all of the tools you need to rewrite the ternary to something even more concise.

const response = "Reed";
const​ username = response ||'guest';
console.log(username); // Reed

As you may have noticed, the best part is that you can append a default value to the end of the expression. This means that you never have to worry about a variable being falsy because you know there’s a truthy value waiting at the end.

So there you have it. You can use short-circuiting to bypass information once something truthy occurs.

How about the other way around? How can you halt an expression once something false occurs? That’s possible as well.

Another popular usage of short-circuiting is to check multiple conditions.

&& short-circuiting

What if we are checking for a valid user, and on top of the user having a real name, they must have verified their email. If not, then they are once again a “guest”.

How can we check to make sure that both conditions are true—a valid name and a verified email?

Let’s write this out in the long format with if statements and we’ll store whether the email is verified in a variable, isEmailVerified. Let’s say we have a name and the email is verified:

const response = "Reed";
const isEmailVerified = true;
let username;
if (response) {
if (isEmailVerified) {
username = response;
}
} else {
username = "guest";
}
console.log(username);

Again, this is a bit verbose. Fortunately, short-circuiting can help. Combining conditionals with the && operator will us to combine the two if conditionals into one.

How does the && operator work? The && operator will stop as soon as a false value occurs and will return the second value if true.

As our experience with the || operator tells us, the && operator can also accept truthy and falsy values.

For example:

const username = "guest" && "A better name";
console.log(username); // ‘A better name’

But if we turn the first value on the left side to a falsy value (an empty string), the conditional stops at the first operand and returns the falsy value without going on to the second.

const username = "" && "A better name";
console.log(username); // ‘’

So how does this help us? For the &&, if the first condition is true it moves onto the next, so instead of having multiple if statements, we can join them all with &&.

Let’s rewrite what we had:

const response = prompt("What’s your name?"); // I type in: Reed
const isEmailVerified = true;
let username;
if (response && isEmailVerified) {
username = response;
} else {
username = "guest";
}
console.log(username); // Reed

This is significantly shorter, but by adding on the ternary operator, we can make it even shorter. Now that we know the && operator works, by returning the second operand, we need to put response second:

const response = "Reed";
const isEmailVerified = true;
// prettier-ignore
const username = isEmailVerified && response || 'guest';
console.log(username); // Reed

Operator precedence

Short-circuiting can be a very powerful technique, but be aware of operator precedence.

Operator precedence means the order in which operators are performed.

For example, do you know whether conditionals with && or || operators are executed first?

&& has higher precedence than ||, so it will always be executed first. You can either keep this in mind when writing your conditionals, or you can set which operators will be executed first using parentheses.

If you want to the || conditional to be executed first, you can wrap that part in parentheses, since parentheses have the highest precedence of all operators in JavaScript:

const username = isEmailVerified && (response || "guest");

Use short-circuiting with caution

Be careful when combining ternaries and short-circuiting. Things can get out of hand very quickly. Though the code is terse, it may be hard for other programmers to understand.

There’s no explicit rule about how many conditionals are too many. It’s more a matter of taste and team agreement. When things get long (I would say around three conditional checks), it’s better to make it a standalone function.

Simplicity is great. It’s fun to try and find clever ways to reduce things to one line, but your goal always communication and readability.

Use short-circuiting to make things simpler and more readable—not to make your code needlessly succinct.



course cover
Join The 2020 JS Bootcamp Video Course 🏕️
Code ArtistryWatch Now
Reed Barger
Professional JS developer who loves to write. Here to make you a better developer, faster.