Counting the Number of Keys using for-in loop

We can also use for-in loop to iterate over the properties of an object and increment a counter for each property encountered. This approach allows us to count the number of keys without relying on any built-in methods.

Syntax:

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

Example: Count the Number of keys using for-in loop. Here, we will count the number of keys in an object using a loop

Javascript




const user = {
    name: "Aman",
    age: 30,
    email: "Aman@example.com",
    address: {
        street: "Sector-15 A-Block",
        city: "Noida",
        state: "Up"
    }
};
 
let count = 0;
for (let key in user) {
    if (user.hasOwnProperty(key)) {
        count++;
    }
}
 
console.log("Number of keys: " + count);


Output

Number of keys: 4


Explanation:

The code initializes an object `user` with nested properties. It iterates through each key of `user` using a for…in loop, increments the count if the property is an own property, and logs the count to the console.

JavaScript Program to Count the Number of Keys/Properties in an Object

An object consists of key-value pairs where each key is a unique identifier associated with a corresponding value.

Several methods can be used to count the number of keys/properties in an object, which are listed below:

Table of Content

  • Counting the Number of Keys using Object.keys
  • Counting the Number of Keys using for-in loop
  • Counting the Number of Keys using Object.getOwnPropertyNames
  • Counting the Number of Keys using Object.entries
  • Counting the Number of Keys using JSON.stringify

Similar Reads

Counting the Number of Keys using Object.keys

The Object.keys() method returns an array of a given object’s enumerable properties, in the same order as they appear in the object. By retrieving the array of keys and calculating its length, we can determine the total number of keys in the object....

Counting the Number of Keys using for-in loop

...

Counting the Number of Keys using Object.getOwnPropertyNames

We can also use for-in loop to iterate over the properties of an object and increment a counter for each property encountered. This approach allows us to count the number of keys without relying on any built-in methods....

Counting the Number of Keys using Object.entries

...

Counting the Number of Keys using JSON.stringify

The Object.getOwnPropertyNames() method returns an array of all properties (including non-enumerable properties) found directly on a given object. We can obtain the array of property names and calculate its length to determine the total number of keys....

Contact Us