Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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?

like image 551
lostdorje Avatar asked Mar 12 '15 07:03

lostdorje


People also ask

What is object keys used for?

keys() The Object. keys() method returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would.

Do object keys have to be unique?

No, JavaScript objects cannot have duplicate keys. The keys must all be unique. There is a good thread on Stack Overflow on this topic. (It is titled with 'associative array', but it really is about a JS Object).

Why does object keys return string?

keys() returns an array whose elements are strings corresponding to the enumerable properties found directly upon object. The ordering of the properties is the same as that given by looping over the properties of the object manually. You get an array of strings, because Property names are strings by definition.


1 Answers

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

like image 109
T.J. Crowder Avatar answered Oct 05 '22 09:10

T.J. Crowder