Saturday, 25 March, 2023 UTC


Summary

At a first glance the Javascript operators Nullish Coalescing ?? and logical OR || are very similar:
// same result for || and ??

const x = null  || 5  
const y = null ?? 5
// x is 5, y is 5
However, there is a difference:
  • the || OR operator uses the right value if the left is falsy (false,
    0, "", null, undefined, NaN)
  • the nullish coalescing operator ?? uses the right value ONLY if the left value is null or undefined
Knowing this, let's take a look at some examples where || and ?? have different outcomes:
// different results for || and ??

const x = false || 5
const y = false ?? 5
// x is 5, y is false

const x = "" || 5
const y = "" ?? 5
// x is 5, y is ""

const x = 0 || 5
const y = 0 ?? 5
// x is 5, y is 0
We can say that the ?? nullish coalescing operator is a subset, a more restrictive version of the || logical OR operator.
By the way, you may find interesting also the double asterisk ** or the double tilde ~~ operators in Javascript.
The post Javascript difference between the ?? (nullish coalescing) vs || (logical OR) operators appeared first on Js Craft.