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.
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.
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 .
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 .
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.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With