0

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.

Mayank
  • 1,351
  • 5
  • 23
  • 42
  • In your second example, `t1` is scoped to `func`, in your first, it's scoped to whatever contains the `for` loop and is shared between all iterations. – James Thorpe Aug 04 '17 at 11:05
  • "So, in first example the value is passed by reference" — In the first example it isn't passed at all. You never give an argument to your function. – Quentin Aug 04 '17 at 11:05

0 Answers0