This is the code:
for (var i = 0; i <= 4; i += (i + 2)) {
var arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
setTimeout(() => {
console.log(arr[i]);
}, 0); // add message to the queue
}
for (var k = 0; k <= 4; k += (k + 2)) {
var arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
((m) => setTimeout(() => console.log(arr[m]), 0))(k) // add message to the queue
}
for (let j = 0; j <= 4; j += (j + 2)) {
let brr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
setTimeout(() => {
console.log(brr[j]);
}, 0); // add message to the queue
}
And the result is: gg from the first loop, ac from the second and third loop.
All callbacks will be put in the queue and will be invoked once the 3 loops are over. My question is why it is gg for the first loop and ac for the third loop and what would be the outer lexical environments at creation time for each callback passed as setTimeout argument?