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 :)