Algorithm


Initialize a variable to hold the count:

javascript
let count = 0;
  • Increment the count for each key:

    javascript
    count = count + 1;
  • Display or return the count:

    javascript
    return count;

Putting it all together:

javascript
function countKeys(object) {
   let count = 0;
   for (let key in object) {
      count = count + 1;
   }
   return count;
}

This function takes an object as a parameter, iterates through its keys, increments the count for each key, and finally returns the total count.

 

Code Examples

#1 Code Example- Count the Number of Key in an Object Using for...in

Code - Javascript Programming

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

const 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);
Copy The Code & Try With Live Editor

Output

x
+
cmd
3

#2 Code Example with Javascript Programming

Code - Javascript Programming

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

const person = {
    gender: 'male'
}

student.__proto__ = person;

let count = 0;

for(let key in student) {

    // increase the count
    ++count;
}

console.log(count); // 4
Copy The Code & Try With Live Editor

#3 Code Example- Count the Number of Key in an Object Using Object.key()

Code - Javascript Programming

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

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

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

console.log(result);
Copy The Code & Try With Live Editor

Output

x
+
cmd
3
Advertisements

Demonstration


JavaScript Programing Example to Count the Number of Keys/Properties in an Object-DevsEnv

Previous
JavaScript Practice Example #3 - Assign 3 Variables and Print Good Way