dev3 ·
My component shows 'Default' when count is 0 because of count || 'Default'. People tell me to use ??. What is the difference, and how does ?. fit in?
0
DEV3 Developer Forum
Every post is reviewed first. Usually reviewed within 24 hours.
My component shows 'Default' when count is 0 because of count || 'Default'. People tell me to use ??. What is the difference, and how does ?. fit in?
|| returns the right side when the left is falsy: false, 0, '', NaN, null, undefined, 0n. ?? returns the right side only when the left is null or undefined.
0 || 10 // 10
0 ?? 10 // 0
'' || 'N/A' // 'N/A'
'' ?? 'N/A' // ''
null ?? 'x' // 'x'
undefined ?? 'x' // 'x'
For defaults where 0, '' or false are valid values, use ??.
?.Stops and returns undefined if the left side is null or undefined.
const city = user?.address?.city;
const first = list?.[0];
const result = obj.method?.(); // call only if it exists
Combine them:
const city = user?.address?.city ?? 'Unknown';
settings.theme ??= 'light'; // assign only if null/undefined
settings.count ||= 1; // assign if falsy
settings.enabled &&= check(); // assign if truthy
a ?? b || c without parentheses is a syntax error. Write (a ?? b) || c.?. does not protect against a non-nullish wrong type ('abc'?.foo.bar still throws on .bar).?. everywhere. If a value must exist, let the error surface rather than hiding bugs.?? and ?. narrow types for you.Pitfall: if (!count) treats 0 as missing, the same bug as ||. Compare to null/undefined explicitly when 0 is valid.