0
0
JavascriptConceptBeginner · 3 min read

Short Circuit Evaluation in JavaScript: What It Is and How It Works

In JavaScript, short circuit evaluation means the language stops checking conditions as soon as the result is known. For AND (&&), if the first value is falsy, it returns that value immediately. For OR (||), if the first value is truthy, it returns that value without checking the rest.
⚙️

How It Works

Short circuit evaluation is like making a quick decision without checking everything. Imagine you want to buy a snack only if you have money and the store is open. If you find out you have no money, you don’t even check if the store is open because you already know you can’t buy the snack.

In JavaScript, this happens with AND (&&) and OR (||) operators. For AND, if the first part is falsy, JavaScript stops and returns that falsy value because the whole condition can’t be true. For OR, if the first part is truthy, it stops and returns that truthy value because the whole condition is already true.

This saves time and can also help avoid errors by not running unnecessary code.

💻

Example

This example shows how short circuit evaluation works with AND and OR operators.

javascript
const a = false;
const b = true;

console.log(a && b); // stops at 'a' because it's falsy
console.log(b || a); // stops at 'b' because it's truthy

// Using short circuit to set default value
const userName = null;
const defaultName = 'Guest';
const displayName = userName || defaultName;
console.log(displayName);
Output
false true Guest
🎯

When to Use

Short circuit evaluation is useful when you want to avoid running code that might cause errors or waste time. For example, you can check if an object exists before accessing its property to prevent errors.

It’s also handy for setting default values, like showing a default name if a user name is missing. This makes your code cleaner and easier to read.

Use it whenever you want to make decisions quickly based on conditions without checking everything.

Key Points

  • AND (&&) stops and returns the first falsy value it finds.
  • OR (||) stops and returns the first truthy value it finds.
  • Helps avoid unnecessary checks and errors.
  • Commonly used for default values and safe property access.

Key Takeaways

Short circuit evaluation stops checking conditions as soon as the result is known.
AND (&&) returns the first falsy value or the last value if all are truthy.
OR (||) returns the first truthy value or the last value if all are falsy.
It helps write safer and more efficient code by avoiding unnecessary checks.
Use it for default values and to prevent errors when accessing properties.