?? vs || in JavaScript: The little-known difference

Safdar Ali - Jul 5 - - Dev Community

At first glance, it might seem like you can interchange ?? (Nullish Coalescing Operator) and || (Logical OR) in JavaScript. However, they are fundamentally different in how they handle truthy and falsy values.

difference

Falsy Values in JavaScript

Falsy values become false in a Boolean context:

  • **0
  • undefined
  • null
  • NaN
  • false
  • '' (empty string)**

false in a Boolean()

Truthy Values

Everything else.

Truthy in a Boolean()

The Difference Explained

  • || (Logical OR): Returns the first truthy value. If the first operand is falsy, it returns the second operand.
let x = 0 || "default"; // "default"
Enter fullscreen mode Exit fullscreen mode

Here, 0 is falsy, so "default" is returned.

  • ?? (Nullish Coalescing): Returns the right-hand operand if the left-hand operand is null or undefined. It ignores other falsy values.
let x = 0 ?? "default"; // 0
Enter fullscreen mode Exit fullscreen mode

Here, 0 is not null or undefined, so 0 is returned.

Use Cases

  • Use || when you want to provide a fallback for any falsy value.
  • Use ?? when you only want to provide a fallback for null or undefined.

Understanding this difference helps avoid bugs and ensures your code behaves as expected.

That's all for today.

And also, share your favourite web dev resources to help the beginners here!

Connect with me:@ LinkedIn and checkout my Portfolio.

Explore my YouTube Channel! If you find it useful.

Please give my GitHub Projects a star ⭐️

Thanks for 24956! 🤗

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .