Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to get the length of an object in JavaScript?
In JavaScript, objects don't have a built-in length property like arrays and strings. When you try to access object.length, it returns undefined. To get the number of properties in an object, you need to use specific methods.
Why Objects Don't Have a Length Property
The length property only works for arrays and strings, not plain objects:
<html>
<body>
<script>
var object = {prop1: 1, prop2: 2};
document.write("Object length: " + object.length);
</script>
</body>
</html>
Object length: undefined
Arrays and Strings Have Length
For comparison, arrays and strings return their actual length:
<html>
<body>
<script>
var string = 'hello';
var array = [1, 2, 3];
document.write("String length: " + string.length);
document.write("<br>");
document.write("Array length: " + array.length);
</script>
</body>
</html>
String length: 5 Array length: 3
Using Object.keys() Method
To get the number of properties in an object, use Object.keys() with the length property:
<html>
<body>
<script>
var object = {one: 1, two: 2, three: 3};
var objectLength = Object.keys(object).length;
document.write("Number of properties: " + objectLength);
</script>
</body>
</html>
Number of properties: 3
Alternative Methods
You can also use Object.entries() or Object.values() to count properties:
<html>
<body>
<script>
var person = {name: "John", age: 30, city: "New York"};
document.write("Using Object.keys(): " + Object.keys(person).length);
document.write("<br>");
document.write("Using Object.entries(): " + Object.entries(person).length);
document.write("<br>");
document.write("Using Object.values(): " + Object.values(person).length);
</script>
</body>
</html>
Using Object.keys(): 3 Using Object.entries(): 3 Using Object.values(): 3
Comparison of Methods
| Method | Returns | Best For |
|---|---|---|
Object.keys(obj).length |
Number of enumerable properties | Most common approach |
Object.entries(obj).length |
Number of key-value pairs | When working with entries |
Object.values(obj).length |
Number of property values | When focusing on values |
Conclusion
Objects in JavaScript don't have a length property. Use Object.keys(obj).length to count the number of properties in an object. This method returns the count of enumerable properties, which represents the object's "length".
