why does i in a for-loop gets overwritten if i use var [duplicate]

i am trying to understand the impact of var from this website http://conceptf1.blogspot.com/2013/11/javascript-closures.html running the … Read more why does i in a for-loop gets overwritten if i use var [duplicate]

i am trying to understand the impact of var from this website http://conceptf1.blogspot.com/2013/11/javascript-closures.html

running the code below shows the results "My value: 3" three times. the explanation for this was given as follows:

because, your myFunctions() is bound to outer-scope variable i which
is changed in each loop so after complete loops it value is 3, that is
the reason it is printing 3 each time.

  1. why does i have a value of 3? the loop ends at i < 3, so shouldn’t i have a value of 2 instead?

  2. when the loop starts: myFunctions[0] My value: 0, followed by myFunctions[1] My value: 1, myFunctions[2] My value: 2. why does the initial values of 0, 1 and 2 in the my value: portion get overwritten?

var funcs = [];
// let's create 3 functions
for (var i = 0; i < 3; i++) {
  // and store them in funcs
  funcs[i] = function test () {
    // each should log its value.
    console.log("My value: " + i);
  };
}

for (var j = 0; j < 3; j++) {
    // and now let's run each one to see
    funcs[j]();
  }

Source: JavaSript – Stack Overflow


Categories: NewsTags: ,

Tags: ,


Leave a Reply

Your email address will not be published. Required fields are marked *