1

I'm interested to know what is the best practice method of checking to see if a child's node exists.

var object = {}

lets say i wanted to access: object.child.element it would return:

Uncaught TypeError: Cannot read property 'element' of undefined

because child is undefined.

I could check each node is defined first:

if (object.child) {
    object.child.element 
}

so this would avoid the TypeError as object.child should be undefined but if we had say 5 elements, having all these if statements wouldn't be a viable solution.

So what i tend to do is wrap the lot in a try.

try {
    var test = object.child.element.foo.bar;
} catch (error) {
    console.log(error);
}

so test would only exist if child, element and foo nodes exist.

Is there a better pattern than this to use?

gardni
  • 1,384
  • 2
  • 24
  • 51
  • I prefer the former approach, and I avoid having too many if statements by designing to avoid it. If I need `object.child.element.foo.bar`, I'll call for `object.getBar()` (which internally checks for a null `child` and returns either `child.getBar()` or null, etc.). – Brian Dec 02 '15 at 16:47

2 Answers2

2

Definitely not the best practice in terms of readability, but I frequently use the following structure (not just for nodes, but generally):

if (object.child && object.child.element)

See it here:

var a = {};
var b = {"child": {}};
var c = {"child": {"element": "finally"}};
         
console.log(a.child && a.child.element);
console.log(b.child && b.child.element);
console.log(c.child && c.child.element);

The code becomes progressively worse the more nesting there is, so you might end up with something ugly as:

object && object.child && object.child.element && object.child.element.another...

However, the good thing is that it works nicely with assignments as well:

var obj = {"child": 123};
var other = obj && obj.child; // 123
Shomz
  • 37,421
  • 4
  • 57
  • 85
0

If you know the names of the properties as strings, you could recursively check for existence.

var properties = ["child", "element", "foo", "bar"];
var i = 0;
var test = obj;
while(i < properties.length && !!test[properties[i]]) {
   test = test[properties[i++]];
}
if(i === properties.length) console.log("success", test);
Kerstomaat
  • 673
  • 4
  • 13