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 isnullorundefined
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.
📖 Build a full trivia game app with LangChain
Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js
📖 Build a full trivia game app with LangChain
Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js