Table of contents
1.
Introduction
2.
1. Using the Object.keys() Method
3.
2. Using for-in Loop and hasOwnProperty() Method
3.1.
Example
4.
3. Using Object.entries() Method
4.1.
Syntax
4.2.
Example
5.
4. Get Length of Object with Object.values()
5.1.
Syntax
5.2.
Example
6.
5. Get Length of Object Using for...in Loop
6.1.
Example
7.
How to Loop through All the Fields of the Object & Check Their Property  
8.
Checking Property Types  
9.
Object.keys vs Object.getOwnPropertyNames
10.
Object Length with Symbols  
10.1.
What are Symbol Properties?  
10.2.
Retrieving Symbol Properties  
10.3.
Calculating Object Length with Symbols  
11.
Practical Use Case  
12.
Frequently Asked Questions
12.1.
What is the easiest way to get the length of an object in JavaScript?
12.2.
Why doesn't JavaScript provide a built-in length property for objects?
12.3.
Which method is best for getting the length of an object?
13.
Conclusion
Last Updated: Feb 9, 2025
Easy

Find the Length of JavaScript object

Author Pallavi singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Finding the length of a JavaScript object helps developers know how many properties an object has. Unlike arrays, objects do not have a direct length property. To count the properties, we can use methods like Object.keys(), Object.values(), or Object.entries(). These methods convert the object into an array, making it easy to count the items. This method is useful when working with data from APIs, filtering information, or managing large datasets.

Find the Length of JavaScript object

In this article, you will learn simple ways to find the length of a JavaScript object, understand its syntax, and see how to use it in real-world coding.

1. Using the Object.keys() Method

`Object.keys()` returns an array of all the enumerable property names of an object. You can then loop through this array to access each property.  

const student = {
  name: "John",
  age: 21,
  course: "Computer Science"
};

const keys = Object.keys(student);  
console.log("Number of properties: " + keys.length);  

keys.forEach(key => {
  console.log(key + ": " + student[key]);
});
You can also try this code with Online Javascript Compiler
Run Code


Explanation:  

1. `Object.keys(student)` returns an array of keys: `["name", "age", "course"]`.  
 

2. `keys.length` gives the number of properties in the object, which is 3 in this case.  
 

3. The `forEach` loop iterates through the array of keys & logs each key-value pair.  
 

4. The output will be:  

Number of properties: 3  
name: John  
age: 21  
course: Computer Science  


This method is more flexible because it allows you to work with the array of keys directly, making it easier to count properties or perform other operations.  

2. Using for-in Loop and hasOwnProperty() Method

The `for...in` loop is a simple way to iterate over all the enumerable properties of an object. Here’s how it works:  

const student = {
  name: "John",
  age: 21,
  course: "Computer Science"
};


for (let key in student) {
  console.log(key + ": " + student[key]);
}
You can also try this code with Online Javascript Compiler
Run Code


Explanation:  

1. We define an object `student` with three properties: `name`, `age`, & `course`.  
 

2. The `for...in` loop iterates over each property in the object.  
 

3. Inside the loop, `key` represents the property name (e.g., `name`, `age`), & `student[key]` gives the corresponding value.  
 

4. The output will be:  

name: John  
age: 21  
course: Computer Science  


This method is simple but has a limitation: it only loops through enumerable properties. If you want to include non-enumerable properties, you’ll need a different approach.  

To ensure only an object's own properties are counted (excluding inherited properties), we use the hasOwnProperty() method.

Example

const student = {
  name: "John",
  age: 22,
  course: "Computer Science"
};

let count = 0;
for (let key in student) {
  if (student.hasOwnProperty(key)) {
    count++;
  }
}
console.log(count); 
You can also try this code with Online Javascript Compiler
Run Code


Output: 

3

 

Explanation:

  • The for...in loop iterates over all properties of student.
     
  • hasOwnProperty(key) ensures that only direct properties are counted.
     
  • count is incremented for each valid property.

3. Using Object.entries() Method

The Object.entries() method returns an array of key-value pairs. The length of this array represents the number of properties.

Syntax

Object.entries(object).length;

Example

const student = {
  name: "John",
  age: 22,
  course: "Computer Science"
};

console.log(Object.entries(student).length); 
You can also try this code with Online Javascript Compiler
Run Code


Output: 

3

 

Explanation:

  • Object.entries(student) returns [["name", "John"], ["age", 22], ["course", "Computer Science"]].
     
  • The length property of this array gives the total number of key-value pairs (3).

4. Get Length of Object with Object.values()

The Object.values() method returns an array of values from an object. The length of this array represents the number of properties.

Syntax

Object.values(object).length;

Example

const student = {
  name: "John",
  age: 22,
  course: "Computer Science"
};

console.log(Object.values(student).length); 
You can also try this code with Online Javascript Compiler
Run Code

Output: 

3

 

Explanation:

  • Object.values(student) returns ["John", 22, "Computer Science"].
     
  • The length property of this array gives the number of properties (3).

5. Get Length of Object Using for...in Loop

We can also use a for...in loop without hasOwnProperty() to count properties. This method is simple but may count inherited properties if not used carefully.

Example

const student = {
  name: "John",
  age: 22,
  course: "Computer Science"
};

let count = 0;
for (let key in student) {
  count++;
}

console.log(count); 
You can also try this code with Online Javascript Compiler
Run Code


Output: 

3

 

Explanation

  • The for...in loop iterates over all properties.
     
  • count is incremented for each iteration.
     
  • This approach may include inherited properties if the object is part of a prototype chain.

How to Loop through All the Fields of the Object & Check Their Property  

When working with objects in JavaScript, you often need to loop through all their fields (properties) to perform certain operations. This is especially useful when you want to count the number of properties in an object, which indirectly helps you determine its length.  

To loop through an object’s fields, you can use methods like `for...in` or combine `Object.keys()` with a loop. 

Checking Property Types  

While looping through object properties, you might also want to check their types. For example, you can determine if a property is a function, object, or primitive value.  

const student = {
  name: "John",
  age: 21,
  course: "Computer Science",
  greet: function() {
    console.log("Hello!");
  }
};

for (let key in student) {
  if (typeof student[key] === 'function') {
    console.log(key + " is a function.");
  } else {
    console.log(key + " is a " + typeof student[key]);
  }
}
You can also try this code with Online Java Compiler
Run Code


Explanation:  

1. The `typeof` operator checks the type of each property value.  

2. If the value is a function, it logs that the property is a function. Otherwise, it logs the type of the value.  

3. The output will be:  

name is a string  
age is a number  
course is a string  
greet is a function.  


This approach helps you understand the structure of an object better, especially when dealing with complex objects.  

Object.keys vs Object.getOwnPropertyNames

ParametersObject.keys()Object.getOwnPropertyNames()
Enumerable PropertiesReturns an array containing only the enumerable properties of an object, which are the properties that appear when using a for...in loop.Returns an array containing all properties of an object (both enumerable and non-enumerable), providing a complete list of the object's direct properties.
Symbol PropertiesDoes not include properties that use Symbol as their key, even if they are enumerable.Does not include Symbol properties in the returned array. To get Symbol properties, use Object.getOwnPropertySymbols().
Inherited PropertiesOnly returns the object's own enumerable properties and excludes properties inherited from the prototype chain.Only returns the object's own properties (including non-enumerable ones) and excludes properties inherited from the prototype chain.
Common Use CasesUsed when iterating over an object's regular enumerable properties, such as when working with plain objects or performing data transformations.Used when accessing all properties of an object, including hidden or non-enumerable properties, which is useful for debugging or inspection.
PerformanceGenerally performs faster since it only checks for enumerable properties.May have slightly lower performance since it checks for all properties, but the difference is usually negligible.
Property DescriptorsOnly considers the enumerable flag of property descriptors when determining which properties to return.Ignores the enumerable flag and returns all properties regardless of their property descriptor settings.

Object Length with Symbols  

In JavaScript, objects can have properties keyed by Symbols, which are unique and immutable primitive values. Symbols are often used to add properties to objects without the risk of naming conflicts. However, when calculating the length of an object, Symbols are not included in methods like `Object.keys()` or `Object.getOwnPropertyNames()`. To handle Symbol properties, JavaScript provides a specific method called `Object.getOwnPropertySymbols()`.  

Let’s discuss how Symbols affect object length and how to work with them.  

What are Symbol Properties?  

Symbols are unique identifiers that can be used as property keys. They are created using the `Symbol()` function.  

Example:  

const id = Symbol('id'); // Creating a Symbol
const student = {
  name: "John",
  age: 21,
  [id]: 12345 // Using the Symbol as a property key
};
console.log(student); 
You can also try this code with Online Javascript Compiler
Run Code

 

Output: 

{ name: "John", age: 21, [Symbol(id)]: 12345 }


Explanation:  

1. We create a Symbol `id` using `Symbol('id')`.  
 

2. The Symbol is used as a property key in the `student` object.  
 

3. When logging the object, the Symbol property is displayed as `[Symbol(id)]: 12345`.  

Retrieving Symbol Properties  

To retrieve Symbol properties from an object, use `Object.getOwnPropertySymbols()`.  

Example:  

const id = Symbol('id');
const grade = Symbol('grade');
const student = {
  name: "John",
  age: 21,
  [id]: 12345,
  [grade]: 'A'
};

const symbols = Object.getOwnPropertySymbols(student);
console.log(symbols); 
You can also try this code with Online Javascript Compiler
Run Code

 

Output: 

[Symbol(id), Symbol(grade)]


Explanation:  

1. We create two Symbols, `id` and `grade`, and use them as property keys in the `student` object.  
 

2. `Object.getOwnPropertySymbols(student)` returns an array of all Symbol properties in the object.  
 

3. The output is `[Symbol(id), Symbol(grade)]`.  

Calculating Object Length with Symbols  

To calculate the total length of an object, including both regular properties and Symbol properties, you can combine `Object.keys()`, `Object.getOwnPropertyNames()`, and `Object.getOwnPropertySymbols()`.  

Example:  

const id = Symbol('id');
const grade = Symbol('grade');
const student = {
  name: "John",
  age: 21,
  [id]: 12345,
  [grade]: 'A'
};

// Get all property names (enumerable & non-enumerable)
const propertyNames = Object.getOwnPropertyNames(student);

// Get all Symbol properties
const symbolProperties = Object.getOwnPropertySymbols(student);

// Calculate total length
const totalLength = propertyNames.length + symbolProperties.length;
console.log("Total length of the object: " + totalLength); 
You can also try this code with Online Javascript Compiler
Run Code

 

Output: 

4


Explanation:  

1. `Object.getOwnPropertyNames(student)` returns `["name", "age"]` (regular properties).  

2. `Object.getOwnPropertySymbols(student)` returns `[Symbol(id), Symbol(grade)]` (Symbol properties).  

3. The total length is calculated by adding the lengths of both arrays, resulting in `4`.  

Practical Use Case  

Symbols are often used to add metadata or hidden properties to objects without interfering with regular property names. For example, you might use Symbols to store internal state or configuration data.  


Example:  

const debugMode = Symbol('debugMode');

const settings = {
  theme: "dark",
  fontSize: 14,
  [debugMode]: true
};

if (settings[debugMode]) {
  console.log("Debug mode is enabled.");
} else {
  console.log("Debug mode is disabled.");
}
You can also try this code with Online Javascript Compiler
Run Code


Explanation:  

1. A Symbol `debugMode` is used to store a hidden property in the `settings` object.  
 

2. The property is accessed using `settings[debugMode]`.  
 

3. Since `debugMode` is a Symbol, it won’t conflict with other property names like `theme` or `fontSize`.  

Frequently Asked Questions

What is the easiest way to get the length of an object in JavaScript?

The simplest way is using Object.keys(object).length, as it directly returns the number of properties.

Why doesn't JavaScript provide a built-in length property for objects?

Objects in JavaScript are designed as collections of key-value pairs, not indexed lists like arrays. Since properties can be dynamically added or removed, a built-in length property could become unreliable.

Which method is best for getting the length of an object?

If you only need to count properties, Object.keys(object).length is the most efficient. If you also need key-value pairs, Object.entries(object).length works well.

Conclusion

In this article, we learned different ways to find the length of a JavaScript object. We discussed methods like using Object.keys(), Object.values(), and Object.entries() to determine the number of properties in an object. Understanding these approaches helps developers efficiently manage and manipulate objects in JavaScript, ensuring better data handling in web applications.

Live masterclass