Some Javascript interview questions.
1. What should be the output of the following code snippet.
const arr = [1, 2, 3, 4];
for (var i = 0; i < arr.length; i++) {
setTimeout(function() {
console.log('Index: ' + i + ', element: ' + arr[i]);
}, 4000);
}
for (var i = 0; i < arr.length; i++) {
setTimeout(function() {
console.log('Index: ' + i + ', element: ' + arr[i]);
}, 4000);
}
Output :
Index: 4 , element: undefined
Explanation :
Actually the setTimeout function will create a closure function which have access to the upper local variable i . So once the for loop gets executed the setTimeout function is get executed and the i value goes up . So within this 1 sec the i value goes upto 4 and the arr[4] value would be undefined .
Nice questions..
ReplyDelete