Here are four ways to get the length of an Object in JavaScript:
- Using Object.keys() method
- Using the for-in loop and hasOwnProperty() method
- Using Object.entries() method
- Using Object.values() method
Method 1: Using the Object.keys() method
The easiest way to get the length of an Object in JavaScript is to use the Object.keys() method that returns an array of the object’s enumerable property names, and you can apply the length property, such as Object. keys(obj).length.
Syntax
Object.keys(obj).length
Example
const obj = { a: 1, b: 2, c: 3, d: 4 };
const length = Object.keys(obj).length;
console.log(length);
Output
4
Method 2: Using the for-in loop and hasOwnProperty() method
The for-in loop iterates over all enumerable properties of an object, including those inherited from prototypes. To ensure you only count the object’s properties, you can use the hasOwnProperty() method.
Example
const obj = { a: 1, b: 2, c: 3, d: 4 };
let length = 0;
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
length++;
}
}
console.log(length);
Output
4
Method 3: Using the Object.entries() method
JavaScript Object.entries() method returns an array of a given object’s enumerable property [key, value] pairs. Similar to the Object.keys() method, you can find the length of this array to get the number of properties in the object.
Syntax
Object.entries(obj).length
Example
const obj = { a: 1, b: 2, c: 3, d: 4 };
const length = Object.entries(obj).length;
console.log(length);
Output
4
Method 4: Using the Object.values() method
JavaScript Object.values() method returns an array of a given object’s enumerable property values. You can then find the length of this array to get the number of properties in the object.
Syntax
Object.values(obj).length
Example
const obj = { a: 1, b: 2, c: 3, d: 4 };
const length = Object.values(obj).length;
console.log(length);
Output
4
Conclusion
If you are dealing with small to medium-sized objects and want a balance of readability and performance, use Object.keys().length, Object.values().length, or Object.entries().length is the best choice.
These methods are fast enough for most applications and offer the benefit of being more straightforward and readable.
Related posts
Check If an Object is Empty in JavaScript
RangeError: invalid array length error

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.