0

With the help of the code, an array is created using a loop, three functions are written to the array. The logic of the functions is simple, the counter value at the time of creation of the function is output to the console. On the surface, the code looks logical, but if you run this code without changes, the number 3 will be output to the console twice. Using the closure mechanism, modify the code to output the number 0 and the number 2 to the console. It is important for me to write in ES5 and use the closure mechanism

var arr = [];

for (var i = 0; i <= 2; i++) {
   arr[i] = function () {
      console.log(i);
   };
}

arr[0](); // 0
arr[arr.length - 1](); // 2
kosmodraiv
  • 29
  • 3
  • Use `let` instead of `var` and your issue will be solved. – Terry Oct 31 '22 at 19:14
  • It is important for me to write ES5 – kosmodraiv Oct 31 '22 at 19:23
  • It's... almost 2023 at this point. No reason to write ES5. Even if you have to, use a transpiler instead: write your code in ES6 and then transpile it down to ES5 if needed. – Terry Oct 31 '22 at 19:25
  • @Terry it's just homework. Centred around closures. And I'd assume hasn't really been updated for maybe a decade. – VLAZ Oct 31 '22 at 19:33

0 Answers0