writing

Nullish Coalescing operator in Javascript

Published on May 18, 2021

Also available in🇻🇳

Nullish Coalescing is a valuable addition in Javascript.

Represent as ?? format, it provides a streamlined approach for working with variables that may be assigned null or undefined values.

When encountering a ?? b expression, the return value will be:

For instance, let’s say we have a user variable, and we want to know if this user has already logged in or not. Firstly, we may use the traditional approach with an if / else condition like this:

let user

if (user) {
  console.log(user)
} else {
  console.log('User not found')
}

// Output: User not found

As demonstrated, if the variable user is not defined, the output will be User not found.

We can achieve the same outcome more concisely with the ternary operator:

let user

console.log(user ? user : 'User not found')

// Output: User not found

Here comes the Nullish Coalescing operator:

let user

console.log(user ?? 'User not found')

// Output: User not found

While the Nullish Coalescing operator may appear similar to the Logical OR operator (||), there is a key difference to consider: the ?? operator specifically targets null and undefined , while || considers all falsy values.

Besides, mixing ?? with those two characters operators && and || can sometimes lead to unexpected results or errors if we don’t pay attention to operator precedence:

const result = value && value.property ?? 'default';

// Error: '&&' and '??' operations cannot be mixed without parentheses.

You wouldn’t want to wait in the economy class line if you bought a business class ticket. Similarly, using parentheses to explicitly define the order of operations is a good way to provide clarity and avoid errors:

let subscribe = (true && !false) ?? false

console.log(subscribe)

// true