Concept Explanation
In JavaScript, logical operators (&&, ||, !, and ??) do more than combine boolean conditions inside an if statement. Because JavaScript evaluates values for truthiness and falsiness, these operators actually return one of their operand values directly and stop evaluating as soon as the outcome is guaranteed—a behavior called short-circuiting.
Every JavaScript value falls into one of two groups when evaluated in a boolean context:
| Category | Values | Behavior in if (val) |
|---|---|---|
| Falsy (all 7 core values) | false, 0, -0, 0n, "", null, undefined, NaN | Treated as false |
| Truthy | "0", "false", [], {}, -1, Infinity, functions | Treated as true |
Notice carefully: an empty array [], an empty object {}, and the non-empty string "0" are all truthy in JavaScript!
How Short-Circuiting Works
Instead of coercing the result to true or false, && and || yield the deciding operand:
- Logical OR (
a || b): Evaluatesa. Ifais truthy, JavaScript stops immediately and returnsawithout touchingb. Otherwise it evaluates and returnsb. - Logical AND (
a && b): Evaluatesa. Ifais falsy, JavaScript stops immediately and returnsawithout touchingb. Otherwise it evaluates and returnsb. - Nullish Coalescing (
a ?? b): Evaluatesa. Only ifaisnullorundefineddoes it fall back tob. Valid values like0,"", andfalseare preserved! - Logical NOT (
!a/!!a): Negates truthiness and always returns a strict boolean. Double negation (Boolean(a)or!!a) explicitly converts any value totrueorfalse.
// 1. Short-circuiting prevents crashes on missing objects
const user = null;
const username = user && user.profile && user.profile.name; // null (no TypeError!)
// Modern equivalent with Optional Chaining + Nullish Coalescing:
const safeName = user?.profile?.name ?? "Guest"; // "Guest"
// 2. Fallback difference: || vs ??
const savedVolume = 0;
console.log(savedVolume || 50); // 50 <-- BUG! 0 is falsy, so default overrides 0
console.log(savedVolume ?? 50); // 0 <-- CORRECT! 0 is not null/undefined
const emptyBio = "";
console.log(emptyBio || "No bio yet"); // "No bio yet" (treats "" as missing)
console.log(emptyBio ?? "No bio yet"); // "" (preserves intentional empty string)
Operator Precedence & Logical Assignment (ES2021)
JavaScript evaluates ! first, then &&, then ||. Mixing && and || without parentheses is a frequent source of subtle bugs—always parenthesize mixed expressions. JavaScript also rejects mixing ?? with && or || without explicit parentheses (SyntaxError).
Modern JavaScript adds logical assignment operators for concise state updates:
const config = { retries: 0, label: "" };
config.retries ??= 3; // Stays 0 (not null/undefined)
config.timeout ??= 5000; // Becomes 5000 (was undefined)
config.label ||= "default"; // Becomes "default" ("" is falsy)
let session = { active: true, user: "Asha" };
session &&= { ...session, seenAt: Date.now() }; // Runs only if session is truthy
Common Mistakes
- The Zero Bug with
||: Writingconst count = inputCount || 10;silently discards a legitimate0. Use??whenever0,false, or""are valid values. - Expecting Side Effects to Always Run: In
isReady() && logAnalytics(),logAnalytics()will never run ifisReady()returns falsy. Never hide mandatory side effects on the right side of&&or||. - Treating
[]or{}as Falsy:if (items)is stilltruewhenitems = []. Always checkitems.length > 0for arrays andObject.keys(obj).length > 0for plain objects. - Mixing
&&and||without Parentheses:isAdmin || isEditor && hasTokenmeansisAdmin || (isEditor && hasToken)because&&binds tighter than||. Use explicit parentheses for clarity.
Best Practices
- Prefer guard clauses (
if (!user) return;) over deeply nestedif/elseblocks. - Prefer
??for configuration defaults, numeric counters, pagination offsets, and boolean flags. - Use
Boolean(value)instead of!!valuewhen readability matters more than brevity.
Practice Exercises
- Truthiness Audit: Predict the return values of
0 || "fallback",0 ?? "fallback","0" && 42, andBoolean([]), then verify each one in the console. - Safe Config Loader: Write a
normalizeSettings(raw)function that preservestimeout: 0anddarkMode: falseusing??, while falling back to sensible defaults when fields are omitted. - Logical Assignment Refactor: Rewrite an
if (cache[key] === undefined) { cache[key] = compute(); }block using??=and verify thatcompute()is not called on a cache hit.