How to get the Length of an Object in JavaScript

avatar

Borislav Hadzhiev

Fri Oct 29 20211 min read

banner

Photo by Stefan Kunze

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.

index.js
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 for...in loop to iterate over the object.

index.js
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 for...in 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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee