Back to home

When to use the operators || or ?? in JavaScript

Jan 3, 2021
2 min read read

Originally written in Spanish on Medium

There are moments when confusion arises, and just when you think you've got everything under control… uncertainty creeps in 💥. I've felt exactly that kind of confusion with these two operators, and since there's no better way to learn than by teaching, I'm writing this first article to clear up the same doubts that came up for me.


Their names are the following: || is called OR, and ?? is known as the Nullish Coalescing Operator. But before diving in, we need to understand what truthy and falsy values are in JavaScript… as you may know, not everything that looks the same is actually equal 🤯. Some truthy values include (basically, anything that's not falsy):

An image representing the different 5 types of truthy values

And the falsy values are the following:

An image representing the different 5 types of falsy values

And… you're almost there! Once you grasp this previous information, using them perfectly will be suuuper easy :)

Our || operator checks for falsy values, while the ?? operator checks only for undefined and null.

An image showing an example of the OR and Nullish Coalescing operator

So, what value do you think our first console.log will return? 🕵️‍♂️🕵️‍♀️ And the second one?

An image showing an example of the Nullish Coalescing Operator with a JavaScript object

Congrats 👏! Our variable a will contain "The best title", and b will have an empty string as its value! And for the more curious ones, here's a bonus… the so-called Logical Nullish Assignment (??=)! As simple as an assignment operator, with the added bonus of our beloved Nullish Coalescing Operator (??).

An image showing an example of the Logical Nullish Assignment

I hope this has been helpful. It's been a pleasure - until next time! 🙌