Get an object's length in JavaScript

An object is not an iterable, so we can't find its length directly; however, there's an easy solution

By: Ajdin Imsirovic 21 January 2021

To get the length of an object in JS, we use Object.keys() to get an array of our object’s own properties’ keys. Then we can easily return the length value.

Get the length of an object in JS

To get the length of an array, we use the built in length property:

let fruits = ['mango','kiwi','lemon'];
fruits.length; // 3

However, we don’t have the length property on objects:

1
2
3
4
5
let tesla = {
    model: 'Model 3',
    mileage: 100
}
tesla.length; // undefined

To go around this, we can use the keys() static method on the Object object. This method takes an object and returns an array of that object’s own keys:

Object.keys(tesla); // (2) ["model", "mileage"]

Since the keys() method returns an array data structure, now it’s easy to count the number of members of the returned array:

let teslaLength = Object.keys(tesla).length;
teslaLength; // 2



Note:
This exercise comes from Book 3 of my book series on JS, available on Leanpub.com.



Feel free to check out my work here: