DEV3 Technologies home

DEV3 Developer Forum

What is the difference between ?? and || in JavaScript, and when do I use ?.?

JavaScript helpSolved0 views
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?

#javascript#operators#nullish

0

1 reply

dev3 · Accepted answer

|| 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 ??.

Optional chaining ?.

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';

Assignment variants

settings.theme ??= 'light';   // assign only if null/undefined
settings.count ||= 1;         // assign if falsy
settings.enabled &&= check(); // assign if truthy

Gotchas

  • 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).
  • Do not use ?. everywhere. If a value must exist, let the error surface rather than hiding bugs.
  • In TypeScript, ?? 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.

0

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.