Speculative object traversal with JavaScript's optional chaining operator

Speculative object traversal with JavaScript's optional chaining operator

3 Oct 2021 javascript

We've all been there. You've received a giant JSON response from some API, you parse it into an object, and you want to reach in several levels deep to retrieve a property if the path exists.

After all, you may not know the exact structure of the object - indeed, its structure may be unpredictable.

Let's say we have this object:

let obj = { foo: { bar: { etc: 'finally!' } } }

What if we want to retrieve the etc property, but we're not sure if the path to it exists? Previously, we'd have had to do something laborious like this:

let etc; if (obj.foo && obj.foo.bar && obj.foo.bar.etc) etc = obj.foo.bar.etc;

If the path doesn't exist - say, if our object was completely empty - and we simply do

let etc = obj.foo.bar.etc;

...we'll get an error saying

Uncaught TypeError: obj.foo is undefined

Makes sense; we're trying to get bar on foo, but foo is undefined, since our object is empty. We could use an object XPath library such as my very own J-Path, but that would probably be overkill until you were doing a lot of this.

These days there's a much cleaner way of dealing with this. ECMAScript 11, which landed last year, brought with it something called the optional chaining operator, which looks like ?..

Now we can simply do:

let etc = obj.foo?.bar?.etc;

If the path exists, we'll get the value. If it doesn't, we'll get undefined - but no show-stopping errors. Pretty cool, right!?

Did I help you? Feel free to be amazing and buy me a coffee on Ko-fi!