Count the Number of Keys/Properties in an Object

 Count the Number of Keys/Properties in an Object

In this example, you will learn to write a JavaScript program that will count the number of keys/properties in an object.

To understand this example, you should have the knowledge of the following JavaScript programming topics:

JavaScript Objects

JavaScript for...in loop

JavaScript Object.keys()


Example 1: Count the Number of Key in an Object Using for...in



The above program counts the number of keys/properties in an object using the for...in loop.

The count variable is initially 0. Then, the for...in loop increases the count by 1 for every key/value in an object.


Example 2: Count the Number of Key in an Object Using Object.key()




In the above program, the Object.keys() method and the length property are used to count the number of keys in an object.

The Object.keys() method returns an array of a given object's own enumerable property names i.e. ["name", "age", "hobbies"].

The length property returns the length of the array.

Post a Comment

Previous Post Next Post