0

let arr = []
for (let i = 0; i < 3; i++) {
  arr.push(function() {
    console.log(i)
  })
}
arr[0]()
arr[1]()
arr[2]()

As far as I know, the function inside the block refers to its lexical environment.

In this case, it will refer to i of block for (let i; …)

When the loop ends, i remains 4.

So, I expected the console to say "3 3 3", but it says "0 1 2".

I concluded that this is because block for acts uniquely, and I wonder why such a result came about.

The expected behavior of block for is just like following two codes below, where the console says "3 3 3"

let arr = []
{
  let i = 0
  while (i < 3) {
   arr.push(function () {
      console.log(i)
    })
  i++
  }
}
arr[0]()
arr[1]()
arr[2]()

or

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

Please tell me why the first case came out with the result "1 2 3".

Alessio Cantarella
  • 5,077
  • 3
  • 27
  • 34
kwonryul
  • 481
  • 3
  • 10

0 Answers0