When to use the operators || or ?? in JavaScript
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):
And the falsy values are the following:
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.
So, what value do you think our first console.log will return? 🕵️♂️🕵️♀️ And the second one?
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 (??).
I hope this has been helpful. It's been a pleasure - until next time! 🙌