Monday, October 9, 2017

Javascript Puzzle No.2 (beginner)

The Object.keys is supposed to return keys (property names) of given object. As the docs says, it should be equivalent of the for...in loop.

Is it really so? This little snippet shows that Object.keys doesn't really enumerate keys but rather ... values.

var p = {
    foo : 0,
    bar : 1
};

for ( var e in p ) {
    console.log( e );
}

for ( var e in Object.keys( p ) ) {
    console.log( e );
}
The snippet prints
foo
bar
0
1
while it definitely should print
foo
bar
foo
bar
What's wrong here?

1 comment:

Unknown said...

I think you need to use the hasOwnProperty function. That is, if(p.hasOwnProperty(e))...
Also, using 0 and 1 was a bit of a red herring because they are the indexes of the items in the resulting array, as well as the values in the object :)