How do `||` and `??` differ when choosing a fallback value?
Quick answer
|| uses the fallback whenever its left-hand value is falsy, so it replaces values such as 0, false, and "". ?? uses the fallback only when the left-hand value is null or undefined; it preserves 0, false, and "". Choose || when every falsy value should trigger a fallback. Choose ?? when only a nullish value should.
The question, the details, the next step.
A practical checklist
Identify which left-hand values can occur, such as
0,false,"",null, orundefined.Decide whether each value is meaningful data or should trigger a fallback.
Choose
??if onlynullorundefinedshould trigger the fallback.Choose
||if every falsy value, including0,false, and"", should trigger it.Check the chosen expression against representative values.
A few more useful answers
Does `??` replace an empty string?
No. It preserves an empty string and uses the fallback only for null or undefined. [S2]
Does `||` replace zero?
Yes. 0 is falsy, so 0 || fallback returns the fallback. [S1]
Which operator should I use for a default setting?
Choose based on the setting’s meaning: use ?? if zero, false, or an empty string may be intentional; use || if those values should also activate the fallback.
Sources
References used for this guide.
- [S1] Logical OR (||) — MDN developer.mozilla.org · Checked
- [S2] Nullish coalescing operator (??) — MDN developer.mozilla.org · Checked
