What is short-circuit evaluation?
Logical operators stop evaluating as soon as the result is known, returning one of the operands rather than a strict boolean.
&& — returns the first falsy value, or the last value if all are truthy. Good for "do this only if that exists" guards.
|| — returns the first truthy value, or the last if all are falsy. Good for defaults.
?? — like ||, but only falls back on null or undefined.
Practical use: const name = user.name || "Guest" supplies a fallback in one expression.
// && — returns first falsy or last value
console.log(true && 'hello'); // 'hello'
console.log(false && 'hello'); // false (short-circuits)
console.log('a' && 'b' && 'c'); // 'c' (all truthy, returns last)
console.log('' && 'hello'); // '' (first falsy)
// Conditional execution
const isAdmin = true;
isAdmin && showAdminPanel(); // Only calls if isAdmin is truthy
// || — returns first truthy or last value
console.log('' || 'default'); // 'default'
console.log(0 || 42); // 42
console.log(null || undefined || 'fallback'); // 'fallback'
// Default values
const name = userInput || 'Anonymous';
// ?? — only null/undefined trigger fallback
const count = 0;
console.log(count || 10); // 10 (WRONG — 0 is falsy)
console.log(count ?? 10); // 0 (CORRECT — 0 is not null/undefined)
const text = '';
console.log(text || 'default'); // 'default' (WRONG — '' is valid)
console.log(text ?? 'default'); // '' (CORRECT)&& short-circuits on first falsy. || short-circuits on first truthy. ?? short-circuits on first non-null/undefined. The critical difference: 0 || 10 = 10 (wrong for counts), 0 ?? 10 = 0 (correct). '' || 'default' = 'default' (wrong for valid empty strings), '' ?? 'default' = '' (correct).
The || vs ?? comparison is the key: || treats ALL falsy as 'missing' (0, '', false), ?? only treats null/undefined as 'missing.' Show the 0 and '' examples where || gives wrong results but ?? gives correct results. && for conditional execution (isAdmin && doThing()) is a common pattern.