- Support for the optional chaining operator came to some major browser releases, allowing for easier and cleaner retrieval of nested object methods and properties given that they exist.*
What is Optional Chaining(?.)
One of the most common operations that us developers need to perform on objects is retrieving its properties and methods. Many times these properties/methods contain other properties/methods that we have to drill down to. However, not every object will have said properties/methods and we end up breaking our code. A common way to handle these errors is to use the &&
operator when drilling down the object, creating a short circuit if the property is returns undefined
const Boat = {
name: {
first: 'Boaty',
last: 'McBoatface'
},
cargo: {
// additional props could reside here
}
}
/**
* check if boat has cargo
* then an item
* then return the quantity of item
*/
const boatQuantity =
boat.cargo &&
boat.cargo.item &&
boat.cargo.item.quantity
We can see that even trying to go only a couple layers deep into an object with the &&
operator things are getting a little messy. However, the optional chaining operator cleans up our code a lot.
// such clean, much readability
const boatQuantity = boat.cargo?.item?.quantity;
Support
Outside of Safari, the latest version of all major browsers now support the optional chaining operator. Alongside them, Babel also provides support so if you're already using Babel in your projects, upgrade to 7.8.3 (maybe earlier? this was the earliest release I could find) and you're good to go.
Thanks for reading! Stay safe and healthy out there everyone
Top comments (0)