JavaScript "cannot read property "bar" of undefined

Connor picture Connor · Nov 4, 2011 · Viewed 143.9k times · Source

I've got a function that takes 3 parameters. The problem I have is one of the parameters is a property of a sometimes undefined value of an Object (i.e. it takes in thing.foo.bar, and sometimes thing.foo is undefined, so it can't access bar).

What's a way around this? Within the function's declaration, I have a conditional checking: if (!parameterName), but the browser (Chrome) is still throwing an error that it can't read the bar property of undefined.

Answer

nnnnnn picture nnnnnn · Nov 4, 2011

If an object's property may refer to some other object then you can test that for undefined before trying to use its properties:

if (thing && thing.foo)
   alert(thing.foo.bar);

I could update my answer to better reflect your situation if you show some actual code, but possibly something like this:

function someFunc(parameterName) {
   if (parameterName && parameterName.foo)
       alert(parameterName.foo.bar);
}