Skip to content

JavaScript object length undefined | Solution

  • by

You will get this error (message in the log) object length undefined in JavaScript if you use the length property in an Object.

Use Object.keys(yourObject).length to get the number of keys (properties) an object has.

JavaScript object length undefined

Simple example code.

<!DOCTYPE html>
<html>
<body>

  <script>
   var coordinates = {
     "a": [
     [1, 2],
     [8, 9],
     [3, 5],
     [6, 1]
     ],

     "b": [
     [5, 8],
     [2, 4],
     [6, 8],
     [1, 9]
     ]
   };

   
   console.log("length" , coordinates.length) 

 </script>

</body>
</html> 

Output:

JavaScript object length undefined

Use the object key method

var coordinates = {
     "a": [
     [1, 2],
     [8, 9],
     [3, 5],
     [6, 1]
     ],

     "b": [
     [5, 8],
     [2, 4],
     [6, 8],
     [1, 9]
     ]
   };

   console.log(Object.keys(coordinates).length) 

Output: 2

Otherwise (notably in IE < 9), you can loop through the object yourself with a for (x in y) loop:

var count = 0;
var i;

for (i in a) {
    if (a.hasOwnProperty(i)) {
        count++;
    }
}

The hasOwnProperty is there to make sure that you’re only counting properties from the object literal, and not properties it “inherits” from its prototype.

Comment if you have any doubts or suggestions on this Js object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *