πŸŽ„ Get 20% off from our JavaScript course for the holidays! πŸŽ„
What are Short Circuits?

What are Short Circuits?

Ferenc Almasi β€’ 2021 January 15 β€’ Read time 1 min read
  • twitter
  • facebook
JavaScript

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:

Copied to clipboard!
const fileName = this.fileName || '😢';
logical-or.js

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:

Copied to clipboard! Playground
let fileName;

if (this.fileName) {
    fileName = this.fileName;
} else {
    fileName = '😢';
}

// or
let fileName = this.fileName;

if (!this.fileName) {
    fileName = '😢';
}
if-else.js

Similarily, you can use logical AND to set a value to true or false, only if all operands are the same:

Copied to clipboard!
hasFireworks && makeItFestive();
logical-and.js

This will only execute the function if hasFireworks is true. It is equivalent to the following if statement:

Copied to clipboard!
if (hasFireworks) {
  makeItFestive();
}
if.js

A common use case is to return a true or false value, based on multiple conditions:

Copied to clipboard!
// 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;
logical-and.js
What are short circuits in JavaScript?
If you would like to see more Webtips, follow @flowforfrank

50 JavaScript Interview Questions

Resources:

Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access exclusive interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Remove ads to learn without distractions
Become a Pro

Recommended