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?

No comments: