
What are Short Circuits?
Short-circuiting, also often called a short circuit evaluation uses logical operations to return early. They are often used as short if statements or setting default values. For example:
const fileName = this.fileName || 'πΆ';
The example above uses the logical OR operator. If this.fileName
is undefined, it will fall back to the provided values after the operator. This is equivalent to an if-else
statement:
let fileName;
if (this.fileName) {
fileName = this.fileName;
} else {
fileName = 'πΆ';
}
// or
let fileName = this.fileName;
if (!this.fileName) {
fileName = 'πΆ';
}
Similarily, you can use logical AND to set a value to true
or false
, only if all operands are the same:
hasFireworks && makeItFestive();
This will only execute the function if hasFireworks
is true. It is equivalent to the following if
statement:
if (hasFireworks) {
makeItFestive();
}
A common use case is to return a true
or false
value, based on multiple conditions:
// Returns true, if all values are evaluated to true
// Returns false, if all values are evaluated to false
return value > this.min && value < this.max;

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