DEV Community

Daniel Engelhardt
Daniel Engelhardt

Posted on • Originally published at hardnold.hashnode.dev on

Why you should use ?? instead of ||

We often see and write things like this:

function sayHey(name) {
  name = name || "Precious";
  console.log(`Hey ${name}`);
}

sayHey("Morty"); //Hey Morty
sayHey(); //Hey Precious
Enter fullscreen mode Exit fullscreen mode

But did you know that the ?? operator, known as the nullish coalescing operator , is often considered safer than the || operator (logical OR) in JavaScript for certain use cases because of how they handle falsy values?

Let me explain...

Understanding Falsy Values

Let's first have a look at what is considered a falsy value in JavaScript. In JavaScript, the following values are considered falsy:

  • false

  • 0 (zero)

  • "" (empty string)

  • null

  • undefined

  • NaN (Not a Number)

How the logical OR (||) works

Now let's have a closer look at what the logical OR (||) operator actually does behind the scenes. || returns the right-hand operand if the left-hand operand is falsy. This is straightforward when you want to default to the right-hand operand only if the left-hand one is null or undefined. However, it can lead to unintended consequences with other falsy values like 0, "", or NaN, which might be valid in your program logic.

Let's look at a simple example to better understand this:

const count = 0;
const defaultCount = count || 10; // defaultCount is 10, not 0
Enter fullscreen mode Exit fullscreen mode

Here, 0 might be a valid value for count , but since 0 is considered falsy, defaultCount becomes 10 instead of 0.

How the nullish coalescing operator (??) works

The nullish coalescing operator (??) in contrast to the logical OR (||) returns the right-hand operand only if the left-hand operand is null or undefined. It does not react to other falsy values like 0, "", or NaN. This makes ?? safer for certain use cases where you want to include these falsy values as valid inputs.

Let's look at our example from above again, but this time using ??:

const count = 0;
const defaultCount = count ?? 10; // defaultCount is 0
Enter fullscreen mode Exit fullscreen mode

Here, defaultCount correctly remains 0 because the nullish coalescing operator only checks for null or undefined, not for any falsy value.

Conclusion

I hope this short article shed some light on the topic when to use ?? over ||. The choice between || and ?? certainly depends on the specific requirements of your code, but next time you want to fallback to default values, I'd encourage you to spend one additional second to evaluate the right operator for your use case. In short:

  • Use || when you want to use a default value for any falsy value.

  • Use ?? when 0, "", or NaN are meaningful values in your context and you only want to fall back to a default for null or undefined

Top comments (0)