I guess, most of the JS developers once came across the following question:
// interviewer: what will the following code output?
const arr = [10, 12, 15, 21];
for (var i = 0; i < arr.length; i++) {
setTimeout(function() {
console.log('Index: ' + i + ', element: ' + arr[i]);
}, 3000);
}
the output is, and it doesn't go as expected.
Index: 4, element: undefined(printed 4 times)
One of the solution is passing the needed parameters into the inner function as following:
const arr = [10, 12, 15, 21];
for (var i = 0; i < arr.length; i++) {
// pass in the variable i so that each function
// has access to the correct index
setTimeout(function(i_local) {
return function() {
console.log('The index of this number is: ' + i_local);
}
}(i), 3000);
}
My confusing point is:
function(i_local) {
return function() {
console.log('The index of this number is: ' + i_local);
}
}(i)
Why we can put (i) after the function statement to pass the parameter? If we directly run this part, it can't run through.
No responses yet.