I am working on this animation function but I have a problem. I can't seem to perform what should be an easy task, I can not get the length of an object. If you check out that jsFiddle you can see that I am running alert(properties.length);
and it is returning undefined
. Can anyone see why this might be?
Objects are used to store the information in key-value pairs, where a value can be any other data type or function. Unlike arrays and strings, objects don't have predefined length property to get the length of an object. So when we call length property on an object it will return undefined.
In a JavaScript program, the correct way to check if an object property is undefined is to use the typeof operator. If the value is not defined, typeof returns the 'undefined' string.
A variable that has not been assigned a value is of type undefined . A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned .
The "Cannot read property 'length' of undefined" error occurs when accessing the length property on an undefined value. To solve the error, make sure to only access the length property on data types that support it - arrays or strings. Here is an example of how the error occurs.
This is supported in node.js and newer environments.
var obj = {a: "a", b: "b"}; Object.keys(obj).length // 2
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