How to Get the Count of Properties in a JavaScript Object

Updated onbyAlan Morel
How to Get the Count of Properties in a JavaScript Object

In JavaScript, objects can be thought of as a collection of key-value pairs.

Objects are used to store data in a structured way, and can represent real-world objects, like a cat.

In some cases, it can be useful to know how many properties an object has.

In this post, we'll learn the two easiest ways to get the number of properties contained inside a JavaScript object.

Using a for loop

The most basic way to get the number of properties in an object is to use a for loop.

Essentially, you iterate over the properties and increment a counter for each property.

First, let's start with an example object:

JAVASCRIPT
const cat = { name: "Fluffy", age: 2, color: "white", isCute: true, };

Next, we'll create a function that takes an object as an argument and returns the number of properties:

JAVASCRIPT
const getNumberOfProperties = obj => { let count = 0; for (const key in obj) { count++; } return count; }

The function takes an object as an argument and initializes a counter variable to 0.

Then, we use a for loop to iterate over the object's properties.

Let's use this function to get the number of properties in our cat object:

JAVASCRIPT
const cat = { name: "Fluffy", age: 2, color: "white", isCute: true, }; const getNumberOfProperties = obj => { let count = 0; for (const key in obj) { count++; } return count; } const count = getNumberOfProperties(cat); console.log(count);
BASH
4

Using Object.keys()

Another way to get the number of properties in an object is to use the Object.keys() method.

This method returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would.

Once we have the array, we can just call the length property to get the number of properties.

Let's give it a try using our earlier example:

JAVASCRIPT
const cat = { name: "Fluffy", age: 2, color: "white", isCute: true, }; const getNumberOfProperties = obj => { return Object.keys(obj).length; } const count = getNumberOfProperties(cat); console.log(count);
BASH
4

Conclusion

In this post, we learned two ways to get the number of properties in a JavaScript object.

The first way is to use a for loop, and the second way is to use the Object.keys() method.

Both methods are easy to understand, so you can choose the one that you prefer.

Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.