Optionaling Chaining in JavaScript
The optional chaining (?.) operator accesses an object's property or calls a function. If the object accessed or function called using this operator is undefined or null, the expression short circuits and evaluates to undefined instead of throwing an error.
Let's understand this by an example.
const address1 = {
apartment: "abc"
}
const address2 = {
flat: "123"
}
let address3;
console.log(address1.flat);
console.log(address2.flat);
console.log(address3.flat);
Output
undefined
123
Uncaught TypeError: Cannot read properties of undefined
This error was resolved traditionally like
if(address3)
console.log(address3.flat);
OR
console.log(address3 && address3.flat);
Using optional chaining:
console.log(address3?.flat);
Output
undefined
This results in shorter and simpler expressions when accessing chained properties when the possibility exists that a reference may be missing. It can also be helpful while exploring the content of an object when there's no known guarantee as to which properties are required.
Optional chaining cannot be used on a non-declared root object, but can be used with a root object with value undefined
let address1;
console.log(address1?.city);
console.log(address2?.city);
Output
undefined
Uncaught ReferenceError: address2 is not defined
Basically, optional chaining checks if address1 is undefined. In this case, it is undefined and hence the output is reduced to undefined, city's value is not even checked.
On the other hand, address 2 is not defined. Hence the error.
To know more about undefined vs not defined, check this artice.
Optional chaining can be used with functions. This may come handy when attempting to call a method which may not exist. For example, when using an API in which a method might be unavailable due to age restriction.
Using optional chaining with function calls causes the expression to automatically return undefined instead of throwing an exception if the method isin't found.
window.abc?.();--undefined
window.abc();Uncaught TypeError: window.abc is not a function
Here optional chaining is checking if `abc` exists and if it's a function.
Optional chaining can be used on arrays as well.
let array;
array[0];Uncaught TypeError: Cannot read properties of undefined
array?.[0];--undefined
The use cases are limitless with optional chaining.