I've been reading Jon Skeet's article on closure capturing strategies and want to explore what's the case with JavaScript.
arr = [];
for(let i = 0; i < 3; i++) {
arr.push(() => console.log(i));
}
arr.forEach(ele => ele());
arr = [];
let j;
for(j = 0; j < 3; j++) {
arr.push(() => console.log(j));
}
arr.forEach(ele => ele());
Surprisingly, the first prints 0,1,2
and the second 3,3,3
.
I also found that JS always captures variables. So why the first case?