1

Consider this code:

var functions = []
for(var i = 0; i < 3; i++) {
    functions.push(function() {
        console.log(i)
    })
}

for(var i = 0; i < 3; i++) {
    functions[i]()
}

//outputs: 
// 1
// 2
// 3


functions.map(function(fn, i) {
    fn()
})

//outputs: 
// 3
// 3
// 3

Why is the output different between the for loop and array.map? Each function in functions array should output the value 3, this is the typical behavior i would expect from my knowledge in Javascript...

melpomene
  • 84,125
  • 8
  • 85
  • 148
Youssef
  • 1,033
  • 8
  • 16
  • 2
    Your second `for` loop is confusing the issue because it reuses (and overwrites) the `i` variable all your functions refer to. Try `i = "hello"; functions[0]();`. – melpomene Jan 02 '17 at 13:16
  • I second that, and would like to add that the map function defines a new i variable as it opens a new scope. It therefore does not overwrite the original i variable and the output is 3, as you would expect – Borre Mosch Jan 02 '17 at 13:17
  • try fn(i) i your code – Jonas Wilms Jan 02 '17 at 13:35

0 Answers0