6

What is the recommended way to check if an object property like obj.prop.otherprop.another is defined?

if(obj && obj.prop && obj.prop.otherprop && obj.prop.otherprop.another) 

this works well, but enough ugly.

2

3 Answers 3

3

The most efficient way to do it is by checking for obj.prop.otherprop.another in a try{} catch(exception){} block. That would be the fastest if all the remaining exist; else the exception would be handled.

var a = null; try { a = obj.prop.otherprop.another; } catch(e) { obj = obj || {}; obj.prop = obj.prop || {}; obj.prop.otherprop = obj.prop.otherprop || {}; obj.prop.otherprop.another = {}; a = obj.prop.otherprop.another ; } 
Sign up to request clarification or add additional context in comments.

1 Comment

Please don't use this.. this is just stupid of me to suggest this.
0

Not saying this is better but ...

x = null try { x = obj.prop.otherprop.another; } catch() {} // ... 

Or alternatively ...

function resolve(obj, path) { path = path.split('.'); while (path.length && obj) obj = obj[path.shift()]; return obj; } x = resolve(obj, 'prop.otherprop.another'); 

... but I guess the actual answer is that there isn't a best-practice for this. Not that I'm aware of.

Comments

0

If you're in a silly mood, this would work:

if ((((obj || {}).prop || {}).anotherprop || {}).another) { ... } 

But I don't know if initializing three new objects is really worth not having to repeatedly type out the path.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.