Reputation: 21
This question was asked during the interview at work interview my answer was recorded as wrong.
Asked Question : What is the output of this code block ?
const arr = [10, 12, 15, 21];
for (var i = 0; i < arr.length; i++) {
setTimeout(function() {
console.log('Index: ' + i + ', element: ' + arr[i]);
}, 3000);
}
My answer is :
index 0 element 10
index 1 element 12
index 2 element 15
index 3 element 21
but it is not correct. What is the right answer ?
Upvotes: 1
Views: 89
Reputation: 147
For your answer using setTimeOut() function, You need to use IIFE - immediately-invoked function expression. Like this
const arr = [10, 12, 15, 21];
for (var i = 0; i < arr.length; i++) {
(function(i){setTimeout(function() {
console.log('Index: ' + i + ', element: ' + arr[i]);
}, 3000)})(i);
}
Because, it for every loop, the entire inner function will get executed and then only the next loop runs. Else, setTimeout function will create timeout events, but loop will be completed and the value of i after loop completion will be here 4 only and the corresponding array element is not there. So, it will be undefined.
For learning about this scenario, Here are some links.
Upvotes: 1
Reputation: 9268
Answer will be :
Index: 4, element: undefined
Index: 4, element: undefined
Index: 4, element: undefined
Index: 4, element: undefined
Explanation :
setTimeout
is used here to print to console, with timeout of 3000 milliseconds or 3 seconds, by that time for
loop will be long over, and at the end of the for
loop, value of i
will be 4.
Since the function inside setTimeout
has the access to variable 'i' (Its called closure
, read about it more here), it will print the value of i = 4
. And since there is no such index 4 in the arr
, it is undefined
.
I hope this clears your doubt.
Upvotes: 1
Reputation: 2535
this is the most popular javascript interview question.
Answer is Index: 4, element: undefined(printed 4 times).
The reason for this is because the setTimeout function creates a function (the closure) that has access to its outer scope, which is the loop that contains the index i. After 3 seconds go by, the function is executed and it prints out the value of i, which at the end of the loop is at 4 because it cycles through 0, 1, 2, 3, 4 and the loop finally stops at 4.arr[4] does not exist, which is why you get undefined.
Upvotes: 3