How to Get the Length of a JavaScript Object?

To get the length of an object, you can simply count the number of own properties an object has (i.e. non-inherited properties that are directly defined on the object). To do that, you can use the following ES5 methods:

  1. Object.keys(myObj).length — get the length of an object based on only the object's own enumerable property names;
  2. Object.getOwnPropertyNames(myObj).length — get the length of all of object's own properties (regardless of whether they're enumerable or not).

Let's consider the following basic example where the object has three own properties:

const obj = { foo: 123, bar: undefined, baz: null };

// ES5+
console.log(Object.keys(obj).length); // output: 3
console.log(Object.getOwnPropertyNames(obj).length); // output: 3

In this case, the result from both methods is the same as both methods give the count of properties directly defined on the object. In contrast to this, let's see an example where the object has own properties/keys as well as inherited ones:

function ExampleObj() {
    this.foo = 123;
}

ExampleObj.prototype.bar = 123;
ExampleObj.prototype.baz = 'qux';

const obj = new ExampleObj();

// ES5+
console.log(Object.keys(obj).length); // output: 1
console.log(Object.getOwnPropertyNames(obj).length); // output: 1

In this example, inherited properties are ignored by both methods and only object's own properties are considered. Therefore, in this case too, both the methods yield the same result.

However, the Object.keys() and Object.getOwnPropertyNames() methods differ in terms of including non-enumerable properties; the former ignores them while the latter includes them. An object property can be made non-enumerable simply by setting its enumerable property descriptor to false. You can see this in the following examples:

const obj = { foo: 123, bar: undefined, baz: null };

// ES5+
Object.defineProperty(obj, 'foo', { enumerable: false });
Object.defineProperty(obj, 'newProp', { enumerable: false });

console.log(Object.keys(obj).length); // output: 2
console.log(Object.getOwnPropertyNames(obj).length); // output: 4
// ES5+
const obj = Object.create({}, {
    foo: { enumerable: false, value: 123 },
    bar: { enumerable: true, value: undefined },
    baz: { enumerable: true, value: null },
});

console.log(Object.keys(obj).length); // output: 2
console.log(Object.getOwnPropertyNames(obj).length); // output: 3

So, depending on whether or not you wish to include enumerable properties in the count of object properties, you can decide to either use Object.keys(myObj).length or Object.getOwnPropertyNames(myObj).length.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.