JavaScriptMedium
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: ifais falsy, returnsaand never evaluatesb; otherwise returnsb.a || b: ifais truthy, returnsaand never evaluatesb; otherwise returnsb.a ?? b: ifais notnullorundefined, returnsa; otherwise returnsb.
Common patterns
- Guard before access:
user && user.name(now usuallyuser?.name). - Conditional execution:
isLoggedIn && showDashboard(). - Defaults:
options.retries ?? 3. - Conditional rendering in React:
{items.length > 0 && <List />}.
Logical assignment (ES2021)
a ||= bassignsbonly ifais falsy.a &&= bassignsbonly ifais truthy.a ??= bassignsbonly ifaisnull/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 />}renders0whencountis0, because&&returns the falsy operand. Usecount > 0 && .... - Using
||for defaults replaces valid0and"". Use??. - Mixing
??with&&or||without parentheses is a syntax error.
Code example
js
1const log = (label, value) => (console.log("evaluated", label), value);23console.log(false && log("right", 1)); // false - right side never runs4console.log(true || log("right", 2)); // true - right side never runs5console.log(null ?? log("fallback", 3)); // runs the fallback, prints 367// Operators return operands, not booleans8console.log("Ada" && "Grace"); // "Grace"9console.log("" || "default"); // "default"10console.log(0 ?? 42); // 01112// Conditional execution13const user = { name: "Ada", isAdmin: true };14user.isAdmin && console.log("show admin panel");1516// Logical assignment17const settings = { theme: "", retries: 0, cache: null };18settings.theme ||= "light"; // "" is falsy -> replaced19settings.retries ??= 3; // 0 is kept20settings.cache ??= new Map(); // null -> replaced21console.log(settings); // { theme: "light", retries: 0, cache: Map(0) {} }2223// The React-style pitfall24const 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.