0

Simple javascript / json question.

In my code I am finding a value for a variable from one of a number of sources (I try each in turn until I find one that is not undefined). One of those sources is a json object with several levels of elements, not all of which are guaranteed to be populated.

Say, for example, the data that I need is found at options.levelA.levelB.levelC.dataThatINeed. None of those levels is guaranteed to be set, including even the options variable itself.

To avoid runtime errors (trying to access a subelement of 'undefined'), is the only safe way to access dataThatINeed to do so as follows:

var data = (options && options.levelA && options.levelA.levelB && options.levelA.levelB.levelC && options.levelA.levelB.levelC.dataThatINeed) || 'default';

It just seems like a very inelegant way to do it, with the real possibility of bugs (typos etc) slipping in with all of those levels to include. I wonder if there is a better practice to adopt. It's a shame you can't access options.levelA.levelB.levelC.dataThatINeed directly, returning undefined if dataThatINeed (or any of the higher levels) is undefined, rather than possibly throwing an error.

Thanks.

drmrbrewer
  • 11,491
  • 21
  • 85
  • 181
  • Yes, that does indeed address the same issue. I do wonder why javascript has not been implemented such that an attempt to access a deeply nested element that has undefined elements along the way does not simply result in `undefined` being returned, rather than throwing an error? To me, `a.b.c` is just as undefined as `a` where `a` has not been defined. – drmrbrewer Mar 23 '15 at 13:21
  • Just seems really inelegant to have to define kludgy ways of accessing `a.b.c` safely, when returning `undefined` where any of `a`, `b` and `c` is undefined seems to be the logical thing to do anyway. – drmrbrewer Mar 23 '15 at 13:23

0 Answers0