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!
Top comments (0)