How to efficiently count the number of keys/properties of an object in JavaScript

count, javascript, key, performance, properties

Solution

To do this in any ES5-compatible environment, such as Node.js, Chrome, Internet Explorer 9+, Firefox 4+, or Safari 5+:

Object.keys(obj).length

- Browser compatibility

- Object.keys documentation (includes a method you can add to non-ES5 browsers)

Problem

What's the fastest way to count the number of keys/properties of an object? Is it possible to do this without iterating over the object? I.e., without doing: ``` var count = 0; for (k in myobj) if (myobj.hasOwnProperty(k)) ++count; ``` (Firefox did provide a magic `__count__` property, but this was removed somewhere around version 4.)

Original source

Related problems