How to get the Length of an Object in JavaScript


Borislav Hadzhiev

Last updated: Oct 29, 2021


Photo from Unsplash

Get the Length of an Object in JavaScript #

To get the length of an object, pass the object to the Object.keys() method and access the length property, e.g. Object.keys(obj).length. The Object.keys method returns an array containing the object's keys, which can be used to determine the object's length.

const obj = {country: 'Chile', city: 'Santiago'}; const length = Object.keys(obj).length; console.log(length); // 👉️ 2

We used the Object.keys method to get an array of the object's keys.

The only parameter the method takes is the object, for which the keys are returned.

The last step is to access the length property on the array to get the number of key-value pairs in the object.

An alternative approach is to initialize a length variable, set it to 0 and use a loop to iterate over the object.

const obj = {country: 'Chile', city: 'Santiago'}; let length = 0; for (const key in obj) { if (obj.hasOwnProperty(key)) { length += 1; } } console.log(length); // 👉️ 2

The loops iterates over the object's enumerable properties, including the inherited ones.

This is why we had to use the Object.hasOwnProperty method to check if the property exists directly on the object or is inherited.

We only increment the length variable if the property exists directly on the object.

The second approach is definitely more verbose and indirect than the first, however you might see it in older code bases.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.