JavaScript Program to 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:


Example 1: Count the number of key in an object using for...in

// program to count the number of keys/properties in an object

let student = { 
    name: 'John',
    age: 20,
    hobbies: ['reading', 'games', 'coding'],
};

let count = 0;

// loop through each key/value
for(let key in student) {

    // increase the count
    ++count;
}

console.log(count);

Output

3

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.

Note: While using the for...in loop, it will also count inherited properties.

For example,

let student = { 
    name: 'John',
    age: 20,
    hobbies: ['reading', 'games', 'coding'],
};

let person = {
    gender: 'male'
}

student.__proto__ = person;

let count = 0;

for(let key in student) {

    // increase the count
    ++count;
}

console.log(count); // 4

If you only want to loop through the object's own property, you can use the hasOwnProperty() method.

if (student.hasOwnProperty(key)) {
    ++count:
}

Example 2: Count the number of key in an object using Object.key()

// program to count the number of keys/properties in an object

let student = { 
    name: 'John',
    age: 20,
    hobbies: ['reading', 'games', 'coding'],
};

let count = 0;

// count the key/value
let result = Object.keys(student).length;

console.log(result);

Output

3

In the above program, the Object.keys() method and the length property is 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.