Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript "cannot read property "bar" of undefined [duplicate]

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.

like image 878
Connor Avatar asked Nov 04 '11 03:11

Connor


People also ask

How do you fix undefined property Cannot be read?

To solve the "Cannot read properties of undefined" error, make sure that the DOM element you are accessing exists. The error is often thrown when trying to access a property at a non-existent index after using the getElementsByClassName() method.

Can not read the property of undefined in JavaScript?

Undefined means that a variable has been declared but has not been assigned a value. In JavaScript, properties and functions can only belong to objects. Since undefined is not an object type, calling a function or a property on such a variable causes the TypeError: Cannot read property of undefined .

What does Cannot read properties of undefined mean?

JavaScript TypeError is thrown when an operand or argument passed to a function is incompatible with the type expected by that operator or function. This error occurs in Chrome Browser when you read a property or call a method on an undefined object .

Can not set property of undefined?

The "Cannot set properties of undefined" error occurs when setting a property on an undefined value. To solve the error, conditionally check if the value is of the expected type (object or array) or has to be initialized before setting the property on it.


1 Answers

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); } 
like image 189
nnnnnn Avatar answered Sep 27 '22 22:09

nnnnnn