javascript - How to check if object within object exists -


it seems following technique checking existence of object member produces error because 'bar' parent object hasn't been declared before check, means either have declare before check or use 2 'typeof' expressions, either of excess code:

var foo = {},     newval = (typeof foo.bar.myval !== 'undefined' ? foo.bar.myval : null );  error: foo.bar undefined 

so, how check if member within undeclared object exists without producing error?

i love javascript, sometimes...

it can done using code below:

var newval = (foo && foo.bar && typeof foo.bar.myval !== 'undefined') ? foo.bar.myval : foo.bar.myval 

a property null or undefined, evaluated false above code process first 'false' statement.


Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -