Stop Letting Nested Object Properties Break Your Code

Use the optional chaining operator (?.) to help with undefined parent properties

Stop Letting Nested Object Properties Break Your Code
Photo by Patrick Baum on Unsplash

If you work with unstructured, unpredictable data then I’m confident that you’ve also seen this error before:TypeError: Cannot read property ‘hello’ of undefined

Inevitably, somebody will send in data in which a deeply nested property’s parent property is undefined. Now, I assume you’ve worked around this potential error — I know I have — but it’s a bit clunky and may look something like this:if(record.education && record.education.bachelors) {
  // do stuff with record.education.bachelors
}

What I’m doing here is checking to make sure that within parent (my top-level variable/object name), the property child is defined. Then, I check that grandchild is defined so that I may do something with greatgrandchild.

For me, I work with data that is many, many levels deep and this type of checking is an eyesore at best, and a show-stopper when you mess it up at worst.

Fortunately, there is a solution!


The Optional Chaining Operator

Rather than throwing a TypeError, if we want the value to return undefined then we can replace the . with ?. which is the optional chaining operator.

Essentially, what the optional chaining operator does is return undefinedif there is a break — undefined or null property— anywhere along the chain.const record = {
 "first_name": "Jonathan",
 "last_name": "Hsu",
 "education": null
};console.log(record.education.bachelors)   // TypeError
console.log(record?.education?.bachelors) // undefined

What this allows you to do is remove the step-by-step checking of each nested property. When checking for a property many levels down, this can save a lot of additional code.


Availability

This new operator is part of the ECMAScript 2020 specification. For full details, refer to their spec doc.

Subscribe to Dreams of Fortunes and Cookies

Sign up now to get access to the library of members-only issues.
Jamie Larson
Subscribe