How to Get the Length of an Object in JavaScript

Here are four ways to get the length of an Object in JavaScript:

  1. Using Object.keys() method
  2. Using the for-in loop and hasOwnProperty() method
  3. Using Object.entries() method
  4. Using Object.values() method

Method 1: Using the Object.keys() method

The easiest way to get the length of an Object in JavaScript is to use the Object.keys() method that returns an array of the object’s enumerable property names, and you can apply the length property, such as Object. keys(obj).length.

Syntax

Object.keys(obj).length

Example

const obj = { a: 1, b: 2, c: 3, d: 4 };

const length = Object.keys(obj).length;

console.log(length); 

Output

4

Method 2: Using the for-in loop and hasOwnProperty() method

The for-in loop iterates over all enumerable properties of an object, including those inherited from prototypes. To ensure you only count the object’s properties, you can use the hasOwnProperty() method.

Example

const obj = { a: 1, b: 2, c: 3, d: 4 };

let length = 0;

for (const key in obj) {
  if (obj.hasOwnProperty(key)) {
    length++;
  }
}
console.log(length); 

Output

4

Method 3: Using the Object.entries() method

JavaScript Object.entries() method returns an array of a given object’s enumerable property [key, value] pairs. Similar to the Object.keys() method, you can find the length of this array to get the number of properties in the object.

Syntax

Object.entries(obj).length

Example

const obj = { a: 1, b: 2, c: 3, d: 4 };

const length = Object.entries(obj).length;

console.log(length);

Output

4

Method 4: Using the Object.values() method

JavaScript Object.values() method returns an array of a given object’s enumerable property values. You can then find the length of this array to get the number of properties in the object.

Syntax

Object.values(obj).length

Example

const obj = { a: 1, b: 2, c: 3, d: 4 };

const length = Object.values(obj).length;

console.log(length);

Output

4

Conclusion

If you are dealing with small to medium-sized objects and want a balance of readability and performance, use Object.keys().length, Object.values().length, or Object.entries().length is the best choice.

These methods are fast enough for most applications and offer the benefit of being more straightforward and readable.

Related posts

Check If an Object is Empty in JavaScript

JavaScript Array Length

RangeError: invalid array length error

Leave a Comment