DEV Community

Cover image for Access to nested object properties
Volker Schukai for schukai GmbH

Posted on

5 1

Access to nested object properties

An Everyday Problem

I think every developer knows the problem and often it is just annoying. An object is missing a certain property and nothing works anymore.

let a = {}
console.log(a.b.c)
Enter fullscreen mode Exit fullscreen mode

The script says goodbye and the browser acknowledges the error with a terse TypeError:

Uncaught TypeError: Cannot read properties of undefined
reading 'c') at :1:5

But the javascript gods heard us and created the Optional chaining

So it is possible to omit missing properties.

console.log(a?.b?.c)
Enter fullscreen mode Exit fullscreen mode

Now we don't get an error message anymore, but get an undefined. That is already wow

The whole thing works not only with objects, but also with arrays and functions.

obj.val?.prop
obj.val?.[expr]
obj.arr?.[index]
obj.func?.(args)
Enter fullscreen mode Exit fullscreen mode

Thank you javascript gods!

Top comments (0)

Visualizing Promises and Async/Await 🤓

async await

☝️ Check out this all-time classic DEV post on visualizing Promises and Async/Await 🤓

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay