user2470628 user2470628 - 4 months ago 41
Javascript Question

for in loop weird behavior

I've got some weird behavior with a for-in loop.

Code:

var obj = {
q:1,
w:2,
e:4,
r:5
};

function test(data) {
for (key in data) {
//do sth;
}
}

function() {
for (key in obj) {
console.log(key);
test({a:1,b:2,c:3});
console.log(key);
}
}();


as i expected the output should be sth like this:

q q w w e e r r

but i got this:

q c w c e c r c

i can't find the logic behind this behavior!
the key variables are scoped lexically !
what's worng with my code?

Answer

You need to declare key with var in both functions. Currently, it's an implicit global variable.

function test(data){
    for (var key in data){
        //do sth;
    }
}

Because it's global, references to key in both function involve the same variable, so the loop in test() messes up the loop in the anonymous function.

(You could use let instead of var if you wanted to, though in this case it would make no difference.)