What's the Difference Between JavaScript Nullish Coalescing and OR Operator?

The JavaScript nullish coalescing operator (??) and the OR operator (||) are both logical operators. However, they differ in the following ways:

  1. The OR operator returns the value on the right if the expression on the left is falsy, while the nullish coalescing operator returns the value on the right if expression on the left is a nullish value (i.e. null or undefined);
  2. The OR operator is supported in all old and modern browsers; the nullish coalescing operator (introduced in ES11) is well-supported in modern browsers.

For example:

'' || 'foo'; // 'foo'
0 || 'foo'; // 'foo'
NaN || 'foo'; // 'foo'
null || 'foo'; // 'foo'
undefined || 'foo'; // 'foo'
// ES11+
'' ?? 'foo'; // ''
0 ?? 'foo'; // 0
NaN ?? 'foo'; // NaN
null ?? 'foo'; // 'foo'
undefined ?? 'foo'; // 'foo'

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.