Member-only story
4 Ways to Safely Access Nested Objects in Vanilla Javascript
How to access nested objects and write safer code
If you’re working with Javascript, chances are you might have encountered a situation where you have had to access a deeply nested object. If everything goes well, you get your data without any problems. That’s great!
However, in reality, we are not always guaranteed that the data exists, but mistakenly assume that it does. I have been in that position multiple times and I often find myself thinking: “How could that value not be populated?”
Thankfully, all we need to prevent these pesky errors is an additional check for undefined
values.
Example of the Error
For those folks who are fortunate to not have seen this before, here’s an example to get you acquainted. Let’s say I have a JavaScript object, representing a music artist that I am interested in.
const macAyres = {
tours: {
nearMe: {
sanFrancisco: {
date: 'Sun Oct 27',
location: 'The Regency Ballroom',
cost: '30.00',
},
},
}
}
If I had mistakenly assumed that this concert was in San Jose and wanted to retrieve the location of the (imaginary) concert, I might have typed something like this: