Optional Chaining In Javascript(?.)
Consider the following piece of code:
const user = {
name: 'Faruk',
surname: 'Nasir',
};
Console logging user.address.city
will result in an Uncaught TypeError
. For that reason, It is always a good idea to check for the validity of a property before chaining a nested property on it. This is what I mean:
if (user.address) {
console.log(user.address.city);
}
The above code won't throw an error because it is checking, firstly, the existence of the address
property and only then, the console.log(user.address.city);
statement will execute. In a situation where city
is not valid, it will return undefined
.
Optional chaining––in javascript––is a syntactic sugar that allows for the shortening of expressions when accessing chained properties in a safe manner, especially when there exists the possibility that such reference is missing. Let's rewrite the above code using optional chaining:
console.log(user.address?.city);
And, that's it! Sweet, right?
Usage with function call
We can conveniently run the following code without the fear of the compiler screaming at us:
user.login?.()
When the login
method is not present in the user object, we will only receive and undefined
response.
Usage with expressions and arrays
// expressions
let nestedProp = obj?.['prop' + 'Name'];
// array
let arrayItem = arr?.[42];
Gotchas
- Optional chaining can not be used on a non-declared root object, but can be used with an undefined root object.