Why are Object.keys() and for ... in different?
Asked Answered
P

1

8

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?

Phillipphillipe answered 12/3, 2015 at 7:45 Comment(1)
for..in loops the prototype too, Object.keys only own properties.Hobbledehoy
I
16

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:

var keys = [];
var key;
for (key in object) {
    if (object.hasOwnProperty(key)) { // But using an internal, non-overrideable
                                      // operation, not literally the method
        keys.push(key);
    }
}

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).

Inae answered 12/3, 2015 at 7:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.