Javascript difference between the ?? (nullish coalescing) vs || (logical OR) operators

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.

📖 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.


Leave a Reply

Your email address will not be published. Required fields are marked *

Home Screencasts Best of Newsletter Search X

📖 50 Javascript, React and NextJs Projects

Hi friend! Before you go, just wanted to let you know about the 50 Javascript, React and NextJs Projects FREE ebook.

One of the best ways to learn is by doing the work. Choose from 8 project categories and get started right away:

  • Business & Real-World
  • Games & Puzzles
  • Fun & Interesting
  • Tools & Libraries
  • Personal & Portfolio
  • Project Add-Ons
  • Productivity
  • Clones

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects complete with project briefs and wireframes!

Keep building and level up! Get all projects as an ebook right to your inbox!

X