DEV Community

Cover image for JavaScript “Optional Chaining Operator”
anu365
anu365

Posted on • Edited on

JavaScript “Optional Chaining Operator”

The optional chaining operator provides a way to simplify accessing values through connected objects when it's possible that a reference or function may be undefined or null.

Things going over my head!!

Lets first understand Problem

I have a response that is nested over multiple objects

const response = {
  human= {
    name: 'Alice',
    age: 10,
    gender: 'Male'
  }
}; 
Enter fullscreen mode Exit fullscreen mode

To access the name property of that object, we can use this snippet right here:

const name = response.human.name;
Enter fullscreen mode Exit fullscreen mode

Temporary workaround

However, is it really safe!! What if response is null or undefined.

How we will make it actually safe.

const name = response && response.human && response.name;
Enter fullscreen mode Exit fullscreen mode

This will work.

Solution

“Optional Chaining Operator” ?. which provides us with a very elegant syntax and fail-safe approach to the issue

const name = response?.human?.name;
Enter fullscreen mode Exit fullscreen mode

With the optional chaining operator (?.), you don't have to explicitly test and short-circuit based on the state of first property of object before trying to access second property.

This is equivalent to the following, except that the temporary variable is in fact not created:

let temp = response.human;
let nestedValue = ((temp === null || temp === undefined) ? undefined : temp.name);
Enter fullscreen mode Exit fullscreen mode
Learn more here:

Learn Optional Chaning: MDN
Next

Top comments (0)