Logical Operators & Short-Circuiting

Logical Operators & Short-Circuiting in JavaScript: In JavaScript, logical operators ( , , , and ) do more than combine boolean conditions inside an statement.

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:

CategoryValuesBehavior in if (val)
Falsy (all 7 core values)false, 0, -0, 0n, "", null, undefined, NaNTreated as false
Truthy"0", "false", [], {}, -1, Infinity, functionsTreated 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): Evaluates a. If a is truthy, JavaScript stops immediately and returns a without touching b. Otherwise it evaluates and returns b.
  • Logical AND (a && b): Evaluates a. If a is falsy, JavaScript stops immediately and returns a without touching b. Otherwise it evaluates and returns b.
  • Nullish Coalescing (a ?? b): Evaluates a. Only if a is null or undefined does it fall back to b. Valid values like 0, "", and false are preserved!
  • Logical NOT (!a / !!a): Negates truthiness and always returns a strict boolean. Double negation (Boolean(a) or !!a) explicitly converts any value to true or false.
// 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

  1. The Zero Bug with ||: Writing const count = inputCount || 10; silently discards a legitimate 0. Use ?? whenever 0, false, or "" are valid values.
  2. Expecting Side Effects to Always Run: In isReady() && logAnalytics(), logAnalytics() will never run if isReady() returns falsy. Never hide mandatory side effects on the right side of && or ||.
  3. Treating [] or {} as Falsy: if (items) is still true when items = []. Always check items.length > 0 for arrays and Object.keys(obj).length > 0 for plain objects.
  4. Mixing && and || without Parentheses: isAdmin || isEditor && hasToken means isAdmin || (isEditor && hasToken) because && binds tighter than ||. Use explicit parentheses for clarity.

Best Practices

  • Prefer guard clauses (if (!user) return;) over deeply nested if/else blocks.
  • Prefer ?? for configuration defaults, numeric counters, pagination offsets, and boolean flags.
  • Use Boolean(value) instead of !!value when readability matters more than brevity.

Practice Exercises

  1. Truthiness Audit: Predict the return values of 0 || "fallback", 0 ?? "fallback", "0" && 42, and Boolean([]), then verify each one in the console.
  2. Safe Config Loader: Write a normalizeSettings(raw) function that preserves timeout: 0 and darkMode: false using ??, while falling back to sensible defaults when fields are omitted.
  3. Logical Assignment Refactor: Rewrite an if (cache[key] === undefined) { cache[key] = compute(); } block using ??= and verify that compute() is not called on a cache hit.