What are JavaScript short-circuiting operators?

Commonly, logical operators are used to combine two boolean values. But the truth is that we can do a lot more with the AND and OR operators.

In JavaScript, short-circuiting is the evaluation of an expression from left to right with || and && operators.

If the condition is met and the rest of the conditions won’t affect the already evaluated result, the expression will short-circuit and return that result (value).

Short-circuiting with the or (||) operator

The || operator will return the first truthy value of all the operands, or simply the last value if all of them are falsy.

true || false
// returns true

Code

What do you think the result of this one will be? Run the code to check.

Console

Explanation

In the example below we want to check if the object person contains the job key. To do this, we simply console.log the value of person or for person.job we use OR to get the default string of unemployed.

var person = {
name: 'Jack',
age: 34
}
console.log(person.job || 'unemployed');
// 'unemployed'

Since person.job doesn’t exist, we get undefined. Since undefined is a falsy value, JavaScript will instead go to the other side of the || and accept whatever value is there.

Short-circuiting with the and (&&) operator

The && operator will return false as soon as it gets any falsy value and will return the last true value if all the values are truthy.

true && false
// returns false

Code

Now try to predict the result of this code. Run it to check.

Console

Explanation

It’s possible to take advantage of short-circuiting and to shorten, or even avoid, the if statement.

In the example below, we want to check if an object person key age value is higher than 18. And if yes, we state that this person is allowed to drive.

var person = {
name: 'Jack',
age: 34
}
console.log(person.age > 18 && 'Driving allowed');
// 'Driving allowed'

Since person.age is higher than 18, we get true. In this case, JavaScript has no false value, so the && operator returns the last true value.

To sum it up, for practical applications, we can use the OR operator to set default values, and we can use the AND operator to execute code in the second operand if the first one is true.