Connor Connor - 2 years ago 74
Javascript Question

Javascript "cannot read property "bar" of undefined

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, and sometimes 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.

Thank you!

Answer Source

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 &&

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 &&
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download