Skip to main content

Command Palette

Search for a command to run...

What is Nullish Coalescing and Optional Chaining in JavaScript?

Published
3 min read
What is Nullish Coalescing and Optional Chaining in JavaScript?
T

Web developer with a passion for creating user-friendly websites. Proficient in HTML, CSS, Js, and React.js and open to new opportunities .

As a dynamically-typed language, JavaScript allows for any data type for variables and allows for null or undefined values for values. It can be challenging and frequently involves a lot of error checking and conditional logic to deal with null or undefined values. Two new operators, Optional Chaining and Nullish Coalescing were added to ECMAScript 2020 to aid in the simplification of this procedure. We will examine the distinctions between these two operators in this post, as well as potential usage scenarios.

Both of these features help developers write more concise code by allowing them to easily access nested values within objects without having to worry about errors caused by accessing non-existent properties or undefined values.

Optional Chaining:

Optional chaining is a new operator in ECMAScript 2020 that allows you to safely access properties of an object or call methods on an object without worrying about whether the object is null or undefined. This can be particularly useful when dealing with nested objects, where any one of the objects in the chain might be null or undefined.

The optional chaining operator is denoted by a question mark followed by a period (.?). Here's an example that demonstrates how it works:

const person = {
  name: 'John',
  age: 30,
  address: {
    street: '123 Main St',
    city: 'Anytown',
    state: 'CA'
  }
};

const zip = person.address?.zipCode;

n this example, we're trying to access the zipCode property of the person's address. But what if the address object is null or undefined? In the past, we would need to add some error checking to handle this situation, but with the optional chaining operator, we can simply add a question mark before the period, like this:

const zip = person.address?.zipCode;

Now, if the address object is null or undefined, the optional chaining operator will simply return undefined, and we won't get an error.

Nullish Coalescing:

Nullish coalescing is another new operator in ECMAScript 2020 that allows you to provide a default value when a variable is null or undefined. This can be particularly useful when dealing with function arguments or when assigning default values to variables.

The nullish coalescing operator is denoted by two question marks (??). Here's an example that demonstrates how it works:

const zip = person.address?.zipCode ?? '00000';

In this example, we're using the nullish coalescing operator to provide a default value of '00000' in case the zipCode property is null or undefined.

Difference between Optional Chaining and Nullish Coalescing:

While optional chaining and nullish coalescing might seem similar at first glance, they actually serve different purposes. Optional chaining is used to safely access properties of an object or call methods on an object, while nullish coalescing is used to provide a default value when a variable is null or undefined.

In practice, you might use optional chaining when dealing with nested objects, and nullish coalescing when assigning default values to variables or function arguments. Here's an example that demonstrates how you might use both operators together:

function getAddress(zipCode) {
  const address = getZipCodeLocation(zipCode)?.address ?? 'Unknown';

  return address;
}

In this example, we're using optional chaining to safely access the address property of the zip code location, and nullish coalescing to provide a default value of 'Unknown' in case the address property is null or undefined.

const foo = null ?? 'default string';
console.log(foo);
// Expected output: "default string"

const baz = 0 ?? 42;
console.log(baz);
// Expected output: 0

Conclusion:

Optional Chaining lets us safely access deeply nested object properties without worrying about potential runtime errors whereas Nullish Coalescing helps us define sensible defaults whenever encountering any falsy values during our operations so we don't have unexpected outcomes due unpredictable external sources like API responses etc. Hope this article was helpful!