2 ms·
> for (var i = 0; i < 3; i++) { const log = () => { console.log(i) } setTimeout(log, 100) } > 3, 3, 3 Is this still true? Wasn't there some special
by xg15 5y ago
> for (var i = 0; i < 3; i++) {
const log = () => {
console.log(i)
}
setTimeout(log, 100)
}
> 3, 3, 3
Is this still true? Wasn't there some special behaviour introduced for for(;;) some years ago that "fixed" this?
- ironmagma 5y agoThere are generally no backwards-incompatible changes made to JavaScript, on account of how decades-old websites continue to be supported. The confusion here is that `i` is never snapshotted in time. The variable is captured by the closure, but the only thing captured is the symbol, not the value.
- bigDinosaur 5y agoYes, replace 'var' with 'let' and it ends up correctly scoped. var also gets scoped to the function (or in this case, the window if you just run this loop directly), so you'll even be able to view the value 3 with window.i which is also unexpected. Always use let, I guess.
- deleted 5y ago[deleted]