I have seen this question asked by Google, Amazon and even smaller tech companies to weed out JS developers.
It is a popular and typical closure question:
So what does the code above output after the 3 seconds are up?
Since the original code has const, let’s look at an ES6 solution/fix which is simple:
With you ES6 you can create a solution to the code quickly. By changing var to let, it allows the value of i to be “held” until after the setTimeout is finished.
And then we get what we wanted:
For those not as familiar with ES6, here is an older JS way to solve it: