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.

gariepy
  • 3,518
  • 5
  • 20
  • 34
rrd
  • 1,411
  • 2
  • 15
  • 35

3 Answers3

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 ;
}
jagzviruz
  • 1,283
  • 11
  • 25
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.

broofa
  • 36,284
  • 11
  • 69
  • 73
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.

Bubbles
  • 3,755
  • 1
  • 23
  • 25