While using a delay in a loop i am passing the loop index like below
for (var t = 0; t < 3; t++) {
var t1 = {};
t1['a'] = String(t);
setTimeout(function () {
console.log("Step ", t1);
}, 1000);
}
Edit : Here t1
is a local variable i.e. it is scoped for one iteration only.
And the console output is
Step Object {a: "2"}
Step Object {a: "2"}
Step Object {a: "2"}
And when i wrap the for loop content with a function like below
var func = function (index) {
var t1 = {};
t1['a'] = String(index);
setTimeout(function () {
console.log("Step ", t1);
}, 1000);
};
for (var t = 0; t < 3; t++) {
func(t);
}
The console output is
Step Object {a: "0"}
Step Object {a: "1"}
Step Object {a: "2"}
So, in first example the value is passed by reference and in second it is not.
Can anyone like to explain this behavior.