DEV Community

Matsu
Matsu

Posted on

The Power of Nullish Coalescing and Optional Chaining in JavaScript

The Nullish Coalescing Operator (??) is a relatively recent addition to JavaScript (introduced in ECMAScript 2020). Unlike the logical OR operator (||), which evaluates to the right-hand side if the left-hand side is falsy (including undefined and null), the nullish coalescing operator only considers null or undefined as falsy.

// Using ?? to provide a default value
const username = userInput ?? 'Guest';
Enter fullscreen mode Exit fullscreen mode

In the above example, username is assigned the value of userInput if it's not null or undefined. Otherwise, it defaults to 'Guest'.

Optional Chaining and Nullish Coalescing
Now, let's combine the Nullish Coalescing Operator with Optional Chaining to navigate through nested properties safely.

// Data from API
const userData = {
  id: 1,
  username: 'devmatsu',
  shippingInfo: {
    address: {
      city: 'São Paulo',
      country: 'Brazil'
    }
  }
};

// Using Optional Chaining and ?? to access and provide default values
const userCity = userData?.shippingInfo?.address?.city ?? 'Unknown City';
const userPostalCode = userData?.shippingInfo?.address?.postalCode ?? 'No Postal Code';

console.log(userCity);         // 'São Paulo'
console.log(userPostalCode);   // 'No Postal Code'
Enter fullscreen mode Exit fullscreen mode

In this example, if any of the nested properties is null or undefined, the nullish coalescing operator steps in to provide default values.

Creating Robust Code with the Duo
Combining Optional Chaining and the Nullish Coalescing Operator empowers you to write more robust and concise code. This duo ensures that your application gracefully handles undefined or null values, offering default values when needed.

const userDetails = apiResponse?.userDetails ?? getDefaultUserDetails();
Enter fullscreen mode Exit fullscreen mode

In this scenario, getDefaultUserDetails() is called only if apiResponse?.userDetails is null or undefined.

Whether you're fetching data from APIs or dealing with user inputs, the Nullish Coalescing Operator and Optional Chaining allow you to sail through JavaScript seas with confidence. Embrace these modern JavaScript features to enhance the reliability and readability of your code.

Console You Later!

Top comments (0)