Skip to content
Advertisement

When should I use ?? (nullish coalescing) vs || (logical OR)?

Related to Is there a “null coalescing” operator in JavaScript? – JavaScript now has a ?? operator which I see is in use more frequently. Previously most JavaScript code used ||.

JavaScript

In what circumstances will ?? and || behave differently?

Advertisement

Answer

The OR operator || uses the right value if left is falsy, while the nullish coalescing operator ?? uses the right value if left is null or undefined.

These operators are often used to provide a default value if the first one is missing.

But the OR operator || can be problematic if your left value might contain "" or 0 or false (because these are falsy values):

JavaScript

In many cases, you might only want the right value if left is null or undefined. That’s what the nullish coalescing operator ?? is for:

JavaScript

While the ?? operator isn’t available in current LTS versions of Node (v10 and v12), you can use it with some versions of TypeScript or Node:

The ?? operator was added to TypeScript 3.7 back in November 2019.

And more recently, the ?? operator was included in ES2020, which is supported by Node 14 (released in April 2020).

When the nullish coalescing operator ?? is supported, I typically use it instead of the OR operator || (unless there’s a good reason not to).

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement