
What is Short Circuit Evaluation in JavaScript?
Short circuit evaluation can make your code more concise, and easier to understand, and it can also help you avoid having some TypeErrors
in some cases. So what is short circuit evaluation anyway?
Short-circuit evaluation isΒ the semantics of boolean operators in which the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression. β Wikipedia
There are three logical operators in JavaScript, and these are Logical AND (denoted by &&
), Logical OR (denoted by ||
), and Logical NOT (denoted by !
), from which two can be used for short circuits. They are the logical AND, and logical OR operators.

Logical AND
The logical AND operator, returns the second expression, only if the first expression evaluates to false
. Let's take a look at an example:
// Short circuit (set short ifs) with logical AND
hasFireworks && makeItFestive();
// Is equivalent to:
if (hasFireworks) {
makeItFestive();
}
As you can see from the code example above, this is equivalent to creating an if
statement. Only if hasFireworks
evaluates to true
, it will execute the function defined after it. We can of course also use a ternary operator in order to introduce an else
statement:
hasFireworks ? makeItFestive() : makeItChill();
Logical OR
The Logical OR operator on the other hand returns the first expression if it can be converted to true
. Otherwise, it will look at the next expression and return that instead:
// Short circuit (set default values) with logical OR
const fileName = this.fileName || 'πΆ';
This can be useful for setting default values during variable assignments. If this.fileName
is undefined
, the emoji will be used as a fallback value. You can of course further chain this (just like for the logical AND operator) and it will return with either the first expression that evaluates to true
, or the very last one:
const fileName = this.fileName || this.timestamp || 'πΆ';
If the filename is not set, it will try to use the timestamp. If that is unset as well, it will fallback to the emoji. So starting from the left, we are defining preferences for the file name, and if one of them fails, we try to use the next one in the line.


Resources:
Unlimited access to hundred of tutorials
Access to exclusive interactive lessons
Remove ads to learn without distractions