Hemanth's Scribes

javascript

Nullish Coalescing vs Logical OR

Author Photo

Hemanth HM

Thumbnail

Whenever I talk about ?? people have asked me the difference between Logical OR (||) vs Nullish coalescing (??) operators, so here is a quick explanation.

The Key Difference

  • || returns the right-hand side if left-hand side is falsy (false, 0, ”, null, undefined, NaN)
  • ?? returns the right-hand side only if left-hand side is nullish (null or undefined)

Examples

// With ||
0 || 'default'      // 'default' (0 is falsy)
'' || 'default'     // 'default' (empty string is falsy)
false || 'default'  // 'default' (false is falsy)
null || 'default'   // 'default'
undefined || 'default' // 'default'

// With ??
0 ?? 'default'      // 0 (0 is not nullish)
'' ?? 'default'     // '' (empty string is not nullish)
false ?? 'default'  // false (false is not nullish)
null ?? 'default'   // 'default'
undefined ?? 'default' // 'default'

When to Use Which

Use ?? when:

  • You want to allow 0, '', or false as valid values
  • You only want to provide a default for null or undefined

Use || when:

  • You want a default for any falsy value
#javascript#es2020#tc39
Author Photo

About Hemanth HM

Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.