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

JavaScript nullish coalescing operator vs. 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'

Hope you found this post useful. It was published . Please show your love and support by sharing this post.