JavaScript: Getting the Number of Keys/Properties of an Object

The standard Object implementation (ES5.1 Object Internal Properties and Methods) does not require an Object to track its number of keys/properties, so there should be no standard way to determine the size of an Object without explicitly or implicitly iterating over its keys.

Here are the most commonly used alternatives:

1. ECMAScript’s Object.keys()

Object.keys(obj).length; Works by internally iterating over the keys to compute a temporary array and returns its length. However, Object.keys(obj) is not supported in IE8 and below, Opera and FF 3.6 and below.

  • Pros – Readable and clean syntax. No library or custom code required except a shim if native support is unavailable
  • Cons – Memory overhead due to the creation of the array.

2. Optimizing a for-loop

The slowest part of such a for-loop is generally the .hasOwnProperty() call, because of the function call overhead. So when I just want the number of entries of a JSON object, I just skip the .hasOwnProperty() call if I know that no code did nor will extend Object.prototype.

Otherwise, your code could be very slightly optimized by making k local (var k) and by using prefix-decrement operator (++count) instead of postfix.

Another idea relies on caching the hasOwnProperty method:

3. Library-based solutions

Many library-based examples elsewhere in this topic are useful idioms in the context of their library. From a performance viewpoint, however, there is nothing to gain compared to a perfect no-library code since all those library methods actually encapsulate either a for-loop or ES5 Object.keys (native or shimmed).

Leave a Reply

Your email address will not be published. Required fields are marked *

CAPTCHA