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()
  2. Using the for-in loop and hasOwnProperty()
  3. Using Object.entries()
  4. Using Object.values()

Method 1: Using the Object.keys() method

The Object.keys() method 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 Object.entries()

The 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 Object.values()

The 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

Related posts

Check If an Object is Empty in JavaScript

JavaScript Array Length

RangeError: invalid array length error