var arr = [10, 24, 15, 4];
for (var i = 0; i < arr.length; i++) {
setTimeout(
(function (index) {
return function () {
console.log("index:" + index + " element: " + arr[index]);
};
})(i),
1000
);
}
Output :-
index:0 element: 10
index:1 element: 24
index:2 element: 15
index:3 element: 4
My understanding is that in JavaScript, asynchronous functions (like the callbacks scheduled by setTimeout) are executed only after all synchronous code has run. In this case, I would expect the for loop to complete before any of the setTimeout callbacks are invoked. Since it's declared with var, it should have a function scope, and by the time the setTimeout callbacks are invoked, it should be equal to arr.length (which is 4).
However, the output shows that each callback is logging the correct index and element from the array. This is the case even when I change var to let.
Could someone help me understand why this is the case? How does JavaScript handle the execution of these asynchronous callbacks in relation to the synchronous for loop, and why does the use of var or let not make a difference in this context?
Any insights or resources for further reading would be greatly appreciated.