const street = restaurant && restaurant.address && restaurant.address.street
What we’re doing here is saying, “Do we have restaurant? If so, do we have an address for that restaurant? If so what is the street of that address?” If there was no street for the restaurant, this would be returned as undefined. Before optional chaining, this was the most effective way to check if an object was undefined or null before accessing its properties.
const street = restaurant?.address?.street
This line of code using the optional chaining operator (?.) is equivalent to the above line of code using the && operator. If restaurant or address happen to be undefined or null, our code will simply be returned as undefined as opposed to the error we would get if it was written like this.
const street = restaurant.address.streetUncaught TypeError: Cannot read property 'street' of undefined
Optional chaining is a great tool for simplicity and readability. It has many uses and can even work with function calls. Just like before, these following two lines of code both work on an object that may or may not be defined and are essentially equivalent.
const tableCount = restaurant.getTableCount && restaurant.getTableCount()const tableCount = restaurant.getTableCount?.()
These lines of code both verify that the restaurant variable has a property called “getTableCount” before trying to call that function. If the function does exist it will be called, however if it does not exist it will just return undefined. Other than optionally chaining functions there is still one more helpful usage, optional chaining with arrays.
const firstRestaurant = array && arrayconst firstRestaurant = array?.
Optional chaining is a clean, dynamic, and readable way to prevent errors and access properties when we are not sure if the object is defined.