I have a large json object. I need to access x = a.b.c.d.e.f.g. However b (or c, d, e...) can be undefined. This data structure is being imported from somewhere else.
Is there a way to try to get to assign x with null or undefined without throwing an error?
Update
Optional chaining is now part of the ECMAScript spec and can be used on most javascript clients (browsers, node.js, etc)
To use a default value if the access fails you can use the Nullish coalescing operator (??)
original answer (2017)
The easiest way is to use
try catchThere is a proposal for this called
optional chainingyou can check it here: https://github.com/tc39/proposal-optional-chainingIf you are using a transpiler you'll be able to use it, however its still in the very early stages and might not be accepted to be supported in the spec