Home >Web Front-end >JS Tutorial >Short-Circuit Evaluation in JavaScript: Boost Performance and Simplify Logic!
Ever wondered how JavaScript's ??
, ||
, and &&
operators work under the hood? This article unravels the mystery of short-circuit evaluation, explaining their behavior and highlighting best practices.
Short-circuit evaluation in JavaScript means logical operators assess expressions from left to right, stopping as soon as the outcome is clear.
Logical AND (&&
)
Returns the first falsy value encountered; otherwise, it returns the last value if all are truthy.
<code class="language-javascript">let x = 5; let y = 0; console.log(x && y); // 0 console.log(x && true); // true</code>
Logical OR (||
)
Returns the first truthy value encountered; otherwise, it returns the last value if all are falsy.
<code class="language-javascript">let a = null; let b = "Hello"; console.log(a || b); // Hello console.log(a || false); // false</code>
Nullish Coalescing Operator (??
)
Provides a default value only when the left operand is null
or undefined
.
<code class="language-javascript">let userName = null; let result = 0 ?? 100; console.log(result); // 0 console.log(userName ?? "Guest"); // Guest</code>
Combined Usage (with Best Practices)
Combining these operators requires careful use of parentheses to prevent unexpected results.
<code class="language-javascript">let a = null; let b = 0; let c = 10; let d = 20; let result = (a ?? b) || (c && d); console.log(result); // 20</code>
(a ?? b)
evaluates to 0
(since a
is null
). (c && d)
evaluates to 20
. Therefore, 0 || 20
results in 20
.
Advantages of Short-Circuit Evaluation:
null
or undefined
values.Disadvantages:
Best Practices:
??
over ||
when dealing specifically with null
or undefined
to avoid overriding other falsy values (e.g., 0
, ""
).Short-circuit evaluation isn't unique to JavaScript; it's a common feature in many programming languages (Python, Java, C/C , etc.), though the syntax might differ.
Connect with me on LinkedIn: www.linkedin.com/in/geetansh-chahal-b7473b1b4/
The above is the detailed content of Short-Circuit Evaluation in JavaScript: Boost Performance and Simplify Logic!. For more information, please follow other related articles on the PHP Chinese website!