0

I am a javascript newbie, I face a issue recently, code is below

for (let i=0; i<3; i++) {
  if (i==2) {
    var f = function() {
      console.log("The number: ", i);
    }
  }
}
f();

I thought result is:

The number is 3

but actually, output is:

The number is 2

I feel confuse, so I rewrite it by golang, code below:

var f func() int
for i := 0; i < 3; i++ {
    if i == 2 {
        f = func() int {
            fmt.Println("The number is: ", i)
            return i
        }
    }
}
f()

The golang's output is:

The number is 3

so, why javascript output is those, could someone help me understand, thanks :)

Roger
  • 1
  • 1
  • `let` has block-scope, not function-scope - each iteration of the loop in JS has a separate binding for `i`, and the iteration in which the function was created has scope of `i` being 2. If you used `var`, it'd be 3 – CertainPerformance Aug 07 '21 at 03:30

0 Answers0