Hey there, welcome!
Today, we’re diving into a crucial JavaScript concept — one that's often confusing for beginners and can lead to serious bugs when misunderstood:
👉 Short-circuiting in JavaScript
🧠 What Is Short-Circuiting?
Short-circuiting means JavaScript stops evaluating an expression as soon as it determines the final result. This can optimize performance and prevent unnecessary computation.
It’s most commonly used with:
-
||(Logical OR) -
&&(Logical AND) -
??(Nullish Coalescing)
Let’s break each one down with clear examples.
1️⃣ || OR Operator – Returns the First Truthy Value
The OR (||) operator evaluates from left to right and returns the first truthy value it encounters. If all values are falsy, it returns the last one.
console.log("" || false || 4); // ➝ 4
🔍 Why?
-
""→ falsy -
false→ falsy -
4→ truthy ✅ → stops and returns4
2️⃣ && AND Operator – Returns the First Falsy Value
The AND (&&) operator evaluates from left to right and returns the first falsy value. If all values are truthy, it returns the last one.
console.log(1 && "JS" && 0 && "React"); // ➝ 0
🔍 Why?
-
1→ truthy -
"JS"→ truthy -
0→ falsy ❌ → stops and returns0
3️⃣ ?? Nullish Coalescing – Handles Only null and undefined
The Nullish Coalescing (??) operator is a safe fallback tool. It returns the right-hand value only if the left-hand value is null or undefined.
let name;
const age = 0;
console.log(name ?? "John"); // ➝ "John"
console.log(age ?? 25); // ➝ 0 ✅
❗ Unlike
||, this does not treat0,"", orfalseas missing values.
Example:
const name = user.name || "Guest"; // if name is "", fallback to "Guest"
const score = user.score ?? 0; // if score is 0, keep it
🤯 Tricky Examples to Test Your Brain
Here are some interesting short-circuit behavior examples 👇
Example 1:
function sayHi() {
console.log("Hi");
return true;
}
function sayBye() {
console.log("Bye");
return false;
}
sayHi() || sayBye();
// Output: "Hi"
Why?
-
sayHi()returnstrue, sosayBye()never gets called due to short-circuiting.
Example 2:
console.log(null || undefined && "value" || "fallback");
Let’s break it down step-by-step:
-
undefined && "value"→undefined// due to JS operators precedence && evaluates first -
null || undefined→undefined -
undefined || "fallback"→"fallback"✅
🧵 Conclusion
Short-circuiting makes JavaScript expressions cleaner and more efficient. But misusing these operators — especially || vs ?? — can cause subtle bugs.
✨ Always know what values you're trying to guard against — is it all falsy values or just
null/undefined?
I once used || thinking it’d only skip null, and ended up skipping 0 — my pagination broke for hours. Learn from my pain 😅.
Top comments (1)
Some comments may only be visible to logged-in visitors. Sign in to view all comments. Some comments have been hidden by the post's author - find out more