It's because of closures.
Check this out: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures#Creating_closures_in_loops_A_common_mistake
The sample code and your code is essentially the same, it's a common mistake for those don't know "closure".
To put it simple, when your create a handler function inside addEvents()
, it does not just accesses the variable i
from the addEvents()
's environment, but it also "remembers" i
.
And because your handler "remembers" i
, the variable i
won't vanish after addEvents()
was executed.
So when the handler is called, it will use the i
but the variable i
is now, after the for-loop, 3.