Write a JavaScript Program to Count the Number of Keys and Properties in an Object

In JavaScript, objects are a fundamental data type that store a collection of key-value pairs.

In this tutorial, we will discuss how to count the number of keys and properties in an object using JavaScript.

To count the number of keys and properties in an object, we can use the Object.keys() method.

The Object.keys() method returns an array of a given object’s own enumerable property names.

Here is an example of how we can use the Object.keys() method to count the number of keys and properties in an object:

const person = {
  name: "John",
  age: 30,
  occupation: "Programmer",
  country: "USA"
};

const numberOfKeys = Object.keys(person).length;

console.log(numberOfKeys); // Output: 4

In the example above, we defined an object person with four key-value pairs.

We then used the Object.keys() method to get an array of the object’s own enumerable property names, which we stored in a variable called numberOfKeys.

Finally, we logged the value of numberOfKeys to the console, which outputs 4.

In addition to Object.keys(), we can also use the Object.getOwnPropertyNames() method to count the number of keys and properties in an object.

The Object.getOwnPropertyNames() method returns an array of all property names, including non-enumerable properties.

Here is an example of how we can use the Object.getOwnPropertyNames() method to count the number of keys and properties in an object:

const car = {
  make: "Toyota",
  model: "Camry",
  year: 2022,
  color: "blue"
};

const numberOfProperties = Object.getOwnPropertyNames(car).length;

console.log(numberOfProperties); // Output: 4

In the example above, we defined an object car with four key-value pairs.

We then used the Object.getOwnPropertyNames() method to get an array of all the property names, which we stored in a variable called numberOfProperties. Finally, we logged the value of numberOfProperties to the console, which outputs 4.

In conclusion, we can use the Object.keys() and Object.getOwnPropertyNames() methods to count the number of keys and properties in an object in JavaScript.

These methods are simple and straightforward to use and can be very useful in many JavaScript applications.