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)

The script says goodbye and the browser ac…


This content originally appeared on DEV Community and was authored by Volker Schukai

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)

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)

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)

Thank you javascript gods!


This content originally appeared on DEV Community and was authored by Volker Schukai


Print Share Comment Cite Upload Translate Updates
APA

Volker Schukai | Sciencx (2021-11-10T19:58:13+00:00) Access to nested object properties. Retrieved from https://www.scien.cx/2021/11/10/access-to-nested-object-properties/

MLA
" » Access to nested object properties." Volker Schukai | Sciencx - Wednesday November 10, 2021, https://www.scien.cx/2021/11/10/access-to-nested-object-properties/
HARVARD
Volker Schukai | Sciencx Wednesday November 10, 2021 » Access to nested object properties., viewed ,<https://www.scien.cx/2021/11/10/access-to-nested-object-properties/>
VANCOUVER
Volker Schukai | Sciencx - » Access to nested object properties. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/11/10/access-to-nested-object-properties/
CHICAGO
" » Access to nested object properties." Volker Schukai | Sciencx - Accessed . https://www.scien.cx/2021/11/10/access-to-nested-object-properties/
IEEE
" » Access to nested object properties." Volker Schukai | Sciencx [Online]. Available: https://www.scien.cx/2021/11/10/access-to-nested-object-properties/. [Accessed: ]
rf:citation
» Access to nested object properties | Volker Schukai | Sciencx | https://www.scien.cx/2021/11/10/access-to-nested-object-properties/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.