Glossary / Short-circuit evaluation
Short-circuit evaluation
Short-circuit evaluation stops evaluating an expression once the operator’s result is determined. JavaScript’s &&, ||, ??, optional chaining, and conditional operator evaluate only the needed parts. Logical operators return operand values, not necessarily booleans, which makes short-circuiting useful for fallback and guarded access but can also hide side effects.
Evaluation order and return values
const user = null;
const name = user && user.name; // null; the right side is skipped
const label = user || "Guest"; // "Guest"
const limit = 0 ?? 10; // 0
&& evaluates the right operand only if the left is truthy; || only if the left is falsy; ?? only if the left is nullish. Optional chaining skips property/call continuation when its immediate receiver is nullish. The ternary operator evaluates exactly one branch based on truthiness.
Do not put required effects in a short-circuited expression: valid && save() may skip save, and a future change to valid can change whether the effect happens. Use explicit if statements when control flow matters. Operator precedence also matters; parentheses communicate grouping, and JavaScript requires parentheses when directly mixing ?? with && or ||.
Interview questions
- Does
&&always return true or false? No; it returns one of its operand values. - When does
||evaluate its right side? When the left side is falsy. - Why can short-circuiting cause a bug? Required side effects may be skipped or implicit control flow may be hard to review.
- How make grouping clear? Use parentheses or an explicit
ifstatement.