What is Optional Chaining?
Optional chaining is a syntax feature that allows you to access deeply nested properties within an object without having to check for the existence of each intermediate property. With optional chaining, if any property in the chain is null or undefined, the entire chain evaluates to undefined without throwing an error.
Let’s consider a simple example. Suppose we have an object user
with a nested property address.street
:
|
|
Without optional chaining, you would need to check for the existence of the address
property before accessing the street
property:
|
|
With optional chaining, you can access the street property more concisely:
|
|
If the address
property is null or undefined, the entire expression evaluates to undefined without throwing an error.
Optional Chaining with Function Calls
|
|
You can use optional chaining to call the greet
method only if it exists:
|
|
You can even use this with Array Indices!
Consider an example where you have an array of users, and you want to access the first user’s name:
|
|
In this example, the optional chaining operator is used twice: once to check if the users
array exists, and once to check if the first element in the array exists. If either the users
array or the first element is null or undefined, the expression evaluates to undefined without throwing an error.
Cheer! 🍺