1

I have a function inside a loop that changes it's returned value in each iteration and I want to save all the returning value of the function in an array.

What's wrong with this code:

function riddle() {
    var a = [];
    for (var i = 0; i < 10; i++) {
        a.push(function() {
            return i * i;
        });
    }
    return a;}

// code to test your solution: 

var a = riddle();
var b = [];
for (var i = 0; i < a.length; i++) { b.push(a[i]()); }
console.log(b);

This what supposed to be printed:

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

But instead I get this:

[100, 100, 100, 100, 100, 100, 100, 100, 100, 100]

zero298
  • 25,467
  • 10
  • 75
  • 100
sami610
  • 79
  • 1
  • 7

1 Answers1

6

What's wrong with this code?

The variable i is hoisted to the top of the scope within the function riddle. The anonymous functions generated in the array do indeed close over the local variable i. But the last value of i is 10, so all of them return 100.

By the way, this code will create a truly local variable to the inner function, and perform as you intended.

a.push((
    function(tmp) {
        return function() {
            return tmp*tmp;
        };
})(i));
Joseph Myers
  • 6,434
  • 27
  • 36