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 isnull
orundefined
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.
📖 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.
📖 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.