Index: 4, element: undefined(printed 4 times).
Why is this question so popular?
A user on reddit mentioned that they were asked this question in an Amazon developer interview. I’ve also been asked this type of closure + loop question in interviews myself — even in a Google interview.
I’ve actually covered this question and some solutions in previous posts:
To quote from a previous article:
The reason for this is because the
setTimeoutfunction 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.
arrdoes not exist, which is why you get
There are two popular solutions to the question. One involves passing the needed parameters into the inner function, and the other solution makes use of ES6.