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?