I'm trying to do a bit of browser object discovery, figuring out browser built-ins etc…
I noticed different results when trying to get at the window object's properties (just FYI I'm using Chrome Version 41.0.2272.89 (64-bit)).
Object.keys(window).length;
returns 7 keys. From the docs Object.keys() returns the enumerable properties of an object.
But the docs also say that for ... in
iterates over the enumerable properties of an object. However:
var i = 0;
for (var propertyName in window) {
i++;
}
returns a count of 177.
Why is this different? Shouldn't they both only be returning the count of enumerable properties?
Best Answer
for-in
loops over the object's own enumerable properties and the enumerable properties of its prototype (and its prototype, etc.).Object.keys
only lists the object's own enumerable properties.So
Object.keys
builds an array something like this:Note the
hasOwnProperty
check (it's not really a call to the method, it's an internal check that can't be tricked by replacing the method or similar).