Nullish Coalescing and Optional Chaining
The nullish coalescing operator ?? chooses the right-hand value only when the left-hand side is null or undefined. This differs from ||, which treats every falsy value as a reason to use the fallback.
Optional chaining ?. allows property, method, and element access to stop safely when the preceding value is nullish.
Why ?? Can Be Better Than ||
const pageSize = 0;
console.log(pageSize || 20);
console.log(pageSize ?? 20);
const user = {};
console.log(user.profile?.address?.city ?? 'Unknown');💡 The
|| expression treats zero as falsy and returns 20. The ?? expression preserves zero because zero is not nullish.Key Takeaways
- Use
??when only null and undefined should trigger a fallback. - Use
||when any falsy value should trigger a fallback. - Optional chaining prevents errors while traversing nullish values.
Knowledge Check
What does `0 ?? 10` return?