What is short-circuiting?

Short-circuiting means the logical operators &&, || and ?? stop evaluating as soon as the result is known, and they return one of their operands (not necessarily a boolean).

How each operator decides

  • a && b: if a is falsy, returns a and never evaluates b; otherwise returns b.
  • a || b: if a is truthy, returns a and never evaluates b; otherwise returns b.
  • a ?? b: if a is not null or undefined, returns a; otherwise returns b.

Common patterns

  • Guard before access: user && user.name (now usually user?.name).
  • Conditional execution: isLoggedIn && showDashboard().
  • Defaults: options.retries ?? 3.
  • Conditional rendering in React: {items.length > 0 && <List />}.

Logical assignment (ES2021)

  • a ||= b assigns b only if a is falsy.
  • a &&= b assigns b only if a is truthy.
  • a ??= b assigns b only if a is null/undefined.

These also short-circuit: the right side is not evaluated if no assignment happens, which matters for expensive defaults.

Pitfalls

  • In React, {count && <Badge />} renders 0 when count is 0, because && returns the falsy operand. Use count > 0 && ....
  • Using || for defaults replaces valid 0 and "". Use ??.
  • Mixing ?? with && or || without parentheses is a syntax error.

Code example

js
1const log = (label, value) => (console.log("evaluated", label), value);
2
3console.log(false && log("right", 1)); // false - right side never runs
4console.log(true || log("right", 2)); // true - right side never runs
5console.log(null ?? log("fallback", 3)); // runs the fallback, prints 3
6
7// Operators return operands, not booleans
8console.log("Ada" && "Grace"); // "Grace"
9console.log("" || "default"); // "default"
10console.log(0 ?? 42); // 0
11
12// Conditional execution
13const user = { name: "Ada", isAdmin: true };
14user.isAdmin && console.log("show admin panel");
15
16// Logical assignment
17const settings = { theme: "", retries: 0, cache: null };
18settings.theme ||= "light"; // "" is falsy -> replaced
19settings.retries ??= 3; // 0 is kept
20settings.cache ??= new Map(); // null -> replaced
21console.log(settings); // { theme: "light", retries: 0, cache: Map(0) {} }
22
23// The React-style pitfall
24const count = 0;
25console.log(count && "Badge"); // 0 - would render "0"
26console.log(count > 0 && "Badge"); // false - renders nothing

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app