Concise way of handling javascript null objects -


what want achieve clean code several possible null returns i'm not returning in more 1 place, code easy follow , not nested nightmare. example consider

var toplevel = testdata['key'];//testdata['key'] may null var nextlevel = toplevel['subkey']; //toplevel['subkey'] may null var subsublevel = ... 

my initial thoughts

var toplevel = testdata['key'] || 'error'; 

this @ least stop "cannot x of null" errors i'll have block @ end i'll need check if each of these vars error , if return null , provide appropriate error message (probably associative object).

does have smarter, more concise way of achieving same end result?

i'd javascript's curiously-powerful && operator (the cousin of curiously-powerful || operator you're using):

var toplevel = testdata['key']; var nextlevel = toplevel && toplevel['subkey']; // ... 

if toplevel falsey (null, undefined, , on), nextlevel falsey value (the left-hand operand); if not, right-hand operand evaluated , nextlevel receives value of that. using these kinds of guards, can keep going long want.

var toplevel = testdata['key']; var nextlevel = toplevel && toplevel['subkey']; var nextnextlevel = nextlevel && nextlevel['key3']; var nextnextnextlevel = nextnextlevel && nextnextlevel['key4']; 

this handy when you're expecting object reference, null, or undefined.


Comments

Popular posts from this blog

javascript - jquery or ashx not working -

opencv - DataType<cv::detail::deriv_type>::depth what is it used for -

python 3.x - Mapping specific letters onto a list of words -