Ari Ari - 1 year ago 56
Javascript Question

How to avoid 'cannot read property of undefined' errors?

In my code, I deal with an array that has some entries with many objects nested inside one another, where as some do not. It looks something like the following:

// where this array is hundreds of entries long, with a mix
// of the two examples given
var test = [{'a':{'b':{'c':"foo"}}}, {'a': "bar"}];

This is giving me problems because I need to iterate through the array at times, and the inconsistency is throwing me errors like so:

for (i=0; i<test.length; i++) {
// ok on i==0, but 'cannot read property of undefined' on i==1

I am aware that I can say
if(a.b){ console.log(a.b.c)}
, but this is extraordinarily tedious in cases where there are up to 5 or 6 objects nested within one another. Is there any other (easier) way that I can have it ONLY do the console.log if it exists, but without throwing an error?

Answer Source

What you are doing raises an exception and logically so.

You can always do


But I wouldn't, instead think of your use case.

Why are you accessing data, 6 levels nested that you are unfamiliar of? What use case justifies this?

Usually, you'd like to actually validate what sort of object you're dealing with.

Also, on a side node you should not use statements like if(a.b) because it will return false if a.b is 0 or even if it is "0". Instead check if a.b !== undefined

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download