0
function count() {
    var arr = [];
    for (var i=1; i<=3; i++) {
        arr.push(function () {
            return i * i;
        });
    }
    return arr;
}

var results = count();
var f1 = results[0];
var f2 = results[1];
var f3 = results[2];
f1(); // 16
f2(); // 16
f3(); // 16

I don't understand why all three inputs are 16? I thought there were 1, 4,9

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
  • var squareCount = (function(){ var c = 0; return function(){ c += Math.pow(c, 2); if(c === 0){ c = 1; return c; } return c; } })(); squareCount(); squareCount(); squareCount(); – StackSlave Dec 12 '16 at 03:07

1 Answers1

1

Because each of f1,f2,f3 are function(){ return i * i; } (note theres no argument to that function, the i inside there is the last value i took (4 in this case, because of the for loop).

YoTengoUnLCD
  • 600
  • 7
  • 15
  • but i has been set or execute from 1 to 3, otherwise how come the compiler know it is 4 in the case? –  Dec 12 '16 at 03:00