0

Why the first argument inside IIFE i = 9, but not 10, is that mechanism how while operator work?

var i = 10;
var array = [];

while (i--) {
    (function(i) {
        console.log(i);
        var i = i;
        array.push(function() {
            return i + i;
        });
    })(i);
}
// array[0]() => 18

If I use for operator, first argument in i = 10:

var i = 10;
var array = [];

for(;i>=0;i--) {
    (function(i) {
        console.log(i);
        var i = i;
        array.push(function() {
            return i + i;
        });
    })(i);
}
array[0]() => 20 
Roman
  • 469
  • 5
  • 12
  • 2
    Because `i--` decrements `i` (your for loop decrements only at the end of an iteration) – CertainPerformance Feb 22 '20 at 10:49
  • 1
    Because your loops are NOT equivalent, you can't expect them to behave the same. The equivalent while loop would be `while (i >= 0) {` in the condition and then do the decrement last (e.g. `})(i--);`). – vicpermir Feb 22 '20 at 11:02

0 Answers0