Skip to content

Instantly share code, notes, and snippets.

@taka011239
Last active October 20, 2015 03:11
Show Gist options
  • Save taka011239/1d2c8a811969953e540d to your computer and use it in GitHub Desktop.
Save taka011239/1d2c8a811969953e540d to your computer and use it in GitHub Desktop.
letのblock scop
for (var i = 0; i < 5; i++) {
setTimeout(function () {
console.log(i);
}, i * 1000);
}
// 5, 5, 5, 5, 5
for (let i = 0; i < 5; i++) {
setTimeout(function () {
console.log(i);
}, i * 1000);
}
// 0, 1, 2, 3, 4
@taka011239
Copy link
Author

ループカウンタにletを使うと、iteration毎にiが宣言され、直前のiteration後の値で初期化される。
forブロック内でループカウンタをrebind、closureに引数でループカウンタを渡すことは不要。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment