javascript closure inside loop

Solutions on MaxInterview for javascript closure inside loop by the best coders in the world

showing results for - "javascript closure inside loop"
Diego
29 Aug 2017
1var funcs = [];
2
3function createfunc(i) {
4  return function() {
5    console.log("My value: " + i);
6  };
7}
8
9for (var i = 0; i < 3; i++) {
10  funcs[i] = createfunc(i);
11}
12
13for (var j = 0; j < 3; j++) {
14  // and now let's run each one to see
15  funcs[j]();
16}