Forem

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!

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

typescript

11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!