📙 Understanding Neuronal Networks presale is now open - 20% off discount!

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.

📖 Neural Networks from Scratch - Presale

I'm writing a book about the timeless foundational concepts of neural networks for JavaScript developers. Go from if-else to weights and biases by building tiny AI models from scratch!

📖 Neural Networks from Scratch - Presale

I'm writing a book about the timeless foundational concepts of neural networks for JavaScript developers. Go from if-else to weights and biases by building tiny AI models from scratch!


Leave a Reply

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