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:

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

This exercise comes from Book 3 of my book series on JS, available on