Javascript variable scope
In JS, the only way to create scope is through functions. Unlike other languages that have a more sane approach to programming, there is no block scopes or anything like it. This leads to some curious behavior:
The output is:
Since there is no block scope (or “for” scope for that matter), the reference to “i” inside the setTimeout calls is updated for all functions. I’m using setTimeout here as an example, but the same is true for anything that is called asynchronously.
We need another function to get the desired behavior:
And now it makes sense!
A final reminder: if you care about performance, don’t create a function inside a loop.