Short-Circuit Evaluation
You've written if (user && user.name) without thinking twice about it. But have you ever asked what happens if user is null — does user.name still get evaluated, and crash? It doesn't, and the reason it doesn't is a rule built into nearly every programming language: && and || stop evaluating the instant they already know the answer. That behavior has a name — short-circuit evaluation — and it's doing more work in your code than you probably realize, for better and for worse.
How to read this
Read in order. Phase 1 is the rule itself, in its simplest form. Phase 2 shows the two everyday patterns this rule enables — patterns you've almost certainly used already. Phase 3 is the part worth slowing down for: the gotchas that show up when short-circuiting interacts with side effects and falsy values.
The phases
- Why bother checking the second half — the rule: AND stops at the first false, OR stops at the first true.
- Where this becomes a real pattern — guard checks and default values.
- The gotcha — skipped side effects, and the falsy-value surprise with
||.
Phase 1: Why bother checking the second half →