How to get the length of an object in JavaScript?

JavascriptObject Oriented ProgrammingFront End Technology

The length property is only applicable to arrays and strings. So when we call the length property on an object we will get undefined.

Example

Live Demo

<html>
<body>
<script>
   var object = {prop:1, prop:2};
   document.write(object.length);
</script>
</body>
</html>

Output

undefined

Whereas arrays and strings will display their length when length property is used on them.

Example

Live Demo

<html>
<body>
<script>
   var string = 'hello';
   var array = [1,2,3];
   var len1 = string.length;
   var len2 = array.length;
   document.write(len1);
   document.write("</br>");
   document.write(len2);
</script>
</body>
</html>

Output

5
3

In javascript, we have Object.keys() property, which checks whether there are any properties or not. If we use the length property with Object.keys() then the number of properties will be displayed which is nothing but the length of the object. 

Example

Live Demo

<html>
<body>
<script>
   var object = {one: 1, two:2, three:3};
   document.write(Object.keys(object).length);
</script>
</body>
</html>

Output

3
raja
Published on 05-Jul-2019 12:36:51
Advertisements