Optional Chaining ?. operator in JavaScript Optional Chaining ?. operator in JavaScript

Optional chaining ?. operator is used to access the nested object properties with implicit nullish check.

Overview

How do you access the nested property of an object with nullish ( null and undefined) check? Say we have to access user details from a response of a web api?

You can use a nested ternary operator ? ... : like this:-

const userName = response ? (response.data ? (response.data.user ? response.data.user.name : null) : null) : null;

or you can have nullish check in if condition like this:-

let userName = null;
if(response && response.data && response.data.user){
  userName = response.data.user.name;
}

or even better can make it a single liner chained && condition like this:-

const userName = response && response.data && response.data.user && response.data.user.name;

What is common in above code is that chaining can go really lengthy at times and becomes more difficult to format and read. This is where optional chaining ?. operator comes to the rescue which provides implicit nullish check and make our code even smaller and better.

const userName = response?.data?.user?.name;

Isn’t it?

Syntax

Optional chaining ?. operator is introduced in Javascript ES2020 which has following syntax:-

obj.val?.prop       returns obj.val.prop if val exists, otherwise undefined.
obj.func?.(args)    returns obj.func(args) if func exists, otherwise undefined.
obj.arr?.[index]    returns obj.array[index] if array exists, otherwise undefined.

Using optional chaining ?. operator

Let’s see usage of ?. operator with user object:-

const user = {
  name: "John",
  age: 21,
  homeaddress: {
    country: "USA"
  },
  hobbies: [{name: "Coding"}, {name: "Cooking"}],
  getFirstName: function(){
    return this.name;
  }
}

with Properties

Access a property which exist returns value:-

console.log(user.homeaddress.country); 
// prints "USA";

Access a property which doesn’t exist throws error:-

console.log(user.officeaddress.country); 
// throws error "Uncaught TypeError: Cannot read property 'country' of undefined"

Access a property with Optional chaining operator ?. which doesn’t exist returns undefined:-

console.log(user.officeaddress?.country); 
// prints "undefined"

with Functions

Call a function which exist returns value:-

console.log(user.getFirstName()); 
// prints "John";

Call a function which doesn’t exist throws error:-

console.log(user.getLastName()); 
// throws error "Uncaught TypeError: user.getLastName is not a function";

Call a function with Optional chaining operator ?. which doesn’t exist returns undefined:-

console.log(user.getLastName?.()); 
// prints "undefined"

with Arrays

Access existing index of an array returns value:-

console.log(user.hobbies[0].name); 
// prints "Coding";

Access non-existing index of an array throws error:-

console.log(user.hobbies[3].name); 
// throws error "Uncaught TypeError: Cannot read property 'name' of undefined"

Access non-existing index of an array with Optional chaining operator ?. returns undefined:-

console.log(user.hobbies[3]?.name); 
// prints "undefined"

Access an array which doesn’t exist throws error:-

console.log(user.dislikes[0].name); 
// throws error "Uncaught TypeError: Cannot read property '0' of undefined"

Access an array with Optional chaining operator ?. which doesn’t exist returns undefined:-

console.log(user.dislikes?.[0]?.name); 
// prints "undefined"

with Nullish Coalescing ?? Operator

Now you know that optional chaining operator ?. returns undefined if object doesn’t exist. Sometime you want to return a value instead of undefined which is possible by using Nullish Coalescing ?? operator along with optional chaining ?. operator.

Without Nullish Coalescing ?? Operator, returns undefined:-

const country = user.officeaddress?.country;
console.log(country);
// prints "undefined"

With Nullish Coalescing ?? Operator, returns default value:-

const country = user.officeaddress?.country ?? "USA";
console.log(country);
// prints "USA"