Hi all,

With the current version of the spec, there is no a direct way to find the number of own enumerable properties of an object.

The common pattern is:


Unfortunately the code above creates a temporary array with all of the own enumerable properties, which I think could be avoided if ES provides an API which returns it directly.

Adding anything to Object.prototype is a nonstarter, and it wouldn't work on a null object anyways, so the only alternative here is something like Object.size(obj) - and then, what about non-enumerable keys? What about Symbol keys (enumerable and non-enumerable)? What about inherited keys?

There simply does not exist a universal definition for an object's "size", which is why Object.keys, or Reflect.ownKeys, or Object.getOwnPropertySymbols, or Object.getOwnPropertyNames, or for (var k in obj) { } are all available options to apply your own definition and generate the length.

In many engines Object.keys tends to have an optimised fast-path, making it less expensive than it looks

Here's V8 for example: v8/keys.cc at 1c3b8975a4f986e4c0b07b9704ae39704c614eec · v8/v8 · GitHub

Of course this wouldn't apply to all objects, but neither would Object.size. If called on a proxy with a custom ownKeys hook, it can't skip that.