W3docs

How to Count the Number if Keys/Properties of a JavaScript object

It is frequently necessary to count the number of keys/properties of an object in JavaScript. Find several solutions to that issue in this short tutorial.

One of the most common tasks in programming with JavaScript is how to count the number of keys/properties of an object.

This short tutorial represents several efficient ways to do it.

Solution 1

The fastest way of counting the keys/properties of an object is to use the following code:

Javascript count the number of Keys/Properties

javascript— editable

Solution 2

Another efficient solution is to use the following code:

javascript keys/properties of an object

Object.keys(obj).length

Javascript keys length of an object

javascript— editable

In modern JavaScript engines, .length is cached and computed in O(1) time, so the memory overhead from creating a temporary array is negligible when you only need the count. The main advantage of this code is that it is clean and readable.

Solution 3

The next solution is optimizing a for-loop. The slowest part of a for-loop is the .hasOwnProperty() call, due to the function overhead.

So, whenever you want to get the number of entries of a JSON object, you can just skip the <kbd class="highlighted">.hasOwnProperty() </kbd> call when you know there is nothing to extend the <kbd class="highlighted">Object.prototype</kbd>.

Otherwise, the code might be slightly optimized by transforming key local (<kbd class="highlighted">var key</kbd>) and applying the prefix-increment operator (<kbd class="highlighted">++count</kbd>) instead of postfix.

Let’s demonstrate it in the example below:

Javascript hasOwnProperty

javascript— editable

There is another option, which relies on catching the <kbd class="highlighted">hasOwnProperty</kbd> method, as follows:

Javascript hasOwnProperty

javascript— editable

And, the final solution to counting the number of keys/properties of an object in JavaScript is the following:

Javascript keys/properties of an object

javascript— editable

Defining Objects in JavaScript

JavaScript objects are generally implemented for storing keyed collections of different data and more complex entities.

In JavaScript, objects are involved in all the components of the language; hence you need to understand them as soon as you start to study it. Objects are generated with <kbd class="highlighted">brackets {…}</kbd> and should have a list of properties. The property is a <kbd class="highlighted">“key: value”</kbd>, in which key or property name is a string and value can be any.