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