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,576
  • 6
  • 21
  • 34
rrd
  • 1,441
  • 2
  • 15
  • 36

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,453
  • 12
  • 27
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
  • 37,461
  • 11
  • 73
  • 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,795
  • 1
  • 24
  • 25