Skip to content

JavaScript array length undefined | Code

Objects don’t have a length property, that way most time developers get JavaScript array length undefined error.

A simple solution if you know you don’t have to worry about hasOwnProperty checks would be to do this:

Object.keys(data).length;

Read:

JavaScript array length undefined

Simple example code tries to get the length of an object and use for..in the loop through the object and get values.

<!DOCTYPE html>
<html>
<body>

  <script>

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

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

   console.log(coordinates.length);
   console.log(typeof(coordinates));

   for (var i in coordinates) {
    console.log(coordinates[i]) 
  }
</script>

</body>
</html> 

Output:

JavaScript array length undefined

or Object.keys

var keys = Object.keys(coordinates);

for (var i = 0, len = keys.length; i < len; i++) {
  console.log(coordinates[keys[i]]);
}

Do comment if you have any doubts or suggestions on this JS array length 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 *

This site uses Akismet to reduce spam. Learn how your comment data is processed.