Skip to main content

Command Palette

Search for a command to run...

Nullish Coalescing and Optional Chaining in JavaScript

Updated
5 min read
Nullish Coalescing and Optional Chaining in JavaScript

In JavaScript, Nullish Coalescing and Optional Chaining are two concepts that have revolutionized the way developers write their code. These features were introduced in ECMAScript 2020 and have been widely adopted by developers all over the world.

Nullish Coalescing Operator

The nullish coalescing operator (??) is used to check if a value is null or undefined, and provide a fallback value if that is the case.

The result of a ?? b is:

  • if a is defined, then a,

  • if a isn’t defined, then b.

Here, a value is considered as defined if it is neither null nor undefined.

In other words, ?? returns the first argument if it’s not null/undefined. Otherwise, the second one. It's just a fancy syntax to get the first defined value of the two.

So, here is an example showing what we discussed above:

const a = null;
const value = a ?? 'default';

console.log(value); // Output: 'default'

In the above example, since the value of a is null, the Nullish Coalescing Operator returns the default value which is 'default'.

In the absence of a nullish coalescing operator, we would have written the same thing as follows:

const a = null;
const value = (a !== null && a !== undefined) ? a : 'default';

console.log(value); // Output: 'default'

Why do we use Nullish coalescing operator?

The common use case for ?? is to provide a default value, as shown in the example above.

We can also use a sequence of ?? to select the first value from a list that isn’t null/undefined.

Let’s say we have a user’s data in variables firstName, lastName, or nickName. All of them may be not defined if the user decided not to fill in the corresponding values.

We’d like to display the user name using one of these variables or show “Anonymous” if all of them are null/undefined.

Let’s use the ?? operator for that:

const firstName = undefined;
const lastName = undefined;
const nickName = "Coder";

console.log(firstName ?? lastName ?? nickName ?? "Anonymous"); // Output: Coder

Another use case for the Nullish Coalescing Operator is when dealing with a function that returns a value that could be null or undefined. By using the Nullish Coalescing Operator, you can provide a default value in case the function returns null or undefined. Here is an example:

function getValue() {
  return null;
}

const value = getValue() ?? 'default';
console.log(value); // Output: 'default'

In the above example, since the function 'getValue' returns null, the Nullish Coalescing Operator returns the default value which is 'default'.

The old way - the OR operator

The Nullish Coalescing Operator is similar to the OR operator (||) in JavaScript. However, the OR operator has a quirk that can lead to unexpected results when dealing with falsy values such as an empty string (''). For example, consider the following code:

const value = '' || 'default';
console.log(value); // Output: 'default'

In the above example, the OR operator returns the default value even though the first value is an empty string. This is because the OR(||) operator returns the first truthy value, and an empty string is a falsy value.

Let's see another example:

const height = 0;

console.log(height || 100); // Output: 100
console.log(height ?? 100); // Output: 0

In the above example, the OR(||) operator returns the second value even though the first value is 0. || doesn’t distinguish between false, 0, an empty string "" and null/undefined. They are all the same – falsy values.

This behavior is not always desirable, and that's where the Nullish Coalescing Operator comes in. The Nullish Coalescing Operator returns the default value only if the value is null or undefined(as seen in the example above), which is more predictable.

Optional Chaining Operator

Optional Chaining (?.) allows developers to access nested properties of an object without worrying about whether the intermediate properties are null or undefined.

Let’s take an example:

let user = {}; // user has no address
console.log(user.address.street); //error

This result was expected as user.address is undefined. So an attempt to access user.address.street will result in an error.

So, how can we solve this problem?

The obvious solution would be to check the value using the conditional operator(?), before accessing its property, like this:

let user = {}; // user has no address
console.log(user.address ? user.address.street : undefined); // Output: undefined

It works, there’s no error… But it’s quite inelegant. As you can see, the user.address appears twice in the code.

Optional Chaining to the rescue

The optional chaining (?.) stops the evaluation if the value before (?.) is undefined or null and returns undefined.

In other words, value?.prop:

  • works as value.prop, if value exists,

  • otherwise (when value is undefined/null) it returns undefined.

So the safe way to access the property is:

let user = {}; // user has no address
console.log( user?.address?.street ); // Output: undefined (no error)

The code is short and clean, there’s no duplication at all.

Another advantage of using Optional Chaining is that it can help you avoid errors caused by typos. For example, consider the following code:

const user = {
  name: 'John Doe',
  address: {
    street: '123 Main St',
    city: 'Anytown',
    state: 'CA',
  },
};

console.log(user.adress?.street); // Output: undefined

In the above example, there is a typo in the property name 'address'. Without Optional Chaining, this would result in a TypeError. However, with Optional Chaining, the code returns undefined instead of throwing an error.

Combining Nullish Coalescing and Optional Chaining

By combining these two concepts, developers can write more concise and error-free code. Here is an example:

const user = {
  name: 'Sameer',

};

console.log(user.name?.toLowerCase() ?? "Name doesn't exists");
console.log(user.dogs?.length ?? "User has no dogs");

In the above example, the first console statement will output “sameer” as name property exists in the array. On the other hand, as the dogs property, which should ideally be an array that does not exist. So the “optional chaining” operator will ideally short-circuit the evaluation and return undefined.

Now as we learned above, the “nullish coalescing” operator returns a fallback value if a value is null or undefined. Hence we” ll get "User has no dogs" in the second case.

Conclusion

Overall, Nullish Coalescing and Optional Chaining are great additions to the JavaScript language that have made code more concise, readable, and maintainable. As a developer, it's important to stay up-to-date with the latest features and best practices to write efficient and effective code.

If you want to learn more about these features, I would recommend checking out the official documentation on Nullish Coalescing and Optional Chaining.

I hope you enjoyed reading this blog. Please share your valuable thoughts in the comment section.

Follow me on Twitter: https://twitter.com/imsunilballani

Connect with me on LinkedIn: https://www.linkedin.com/in/sunil-ballani/