Hedge Hedge - 1 year ago 32
Javascript Question

Shorter way to do: if (a !== undefined && a.b !== undefined && a.b.c === 'foo')

If I need to check an attribute of an object, and it's object (and so on) but can't be sure whether the object exists in the first place how can I make the condition simpler than this?

if (a !== undefined && a.b !== undefined && a.b.c === 'foo')


I'm also using LoDash if it has any meaningful function.

Answer Source

if you know that a is in the current scope (like comming in as an argument) you can do
if(a && a.b && a.b.c === 'foo')
but if ther's an chance a is never defined you have to check the type like:
if( typeof a != 'undefined' && a.b && a.b.c === 'foo')

update
when using lodah the has function can give an better syntax (that unlike the get function returns true if the propperty is a falsy value. Thanks @ryeballar): if(lodash.has(a,'b.c')){ console.log(a.b.c); }

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download