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'
}
};
To access the name property of that object, we can use this snippet right here:
const name = response.human.name;
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;
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;
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);
Top comments (0)