0
(function() {
    var index = 0;
    var length = 5;
    for (var index = 0; index < length; index++) {
        setTimeout(function() {
            console.log(index);
        }, 100);
    }
})();

This code outputs 55555

If I change the var to a let, it outputs 12345

I understand that let prevents the index variable from being hoisted to the top of the function scope but, I don't understand how this changes the answer.

h33
  • 1,104
  • 3
  • 16
  • 29
  • "_how this changes the answer_" By creating a block scope within the `for..index` loop body, where the value of `let` declared variable remembers its value on every round. – Teemu Sep 28 '17 at 10:25
  • 1
    Here is also a good article: https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var-to-declare-a-variable – Dream_Cap Sep 28 '17 at 10:31
  • @deceze Closure is not the question, rather it is how `let` works ..? – Teemu Sep 28 '17 at 10:31
  • 1
    @Teemu That is very much explained in the dupe as well. The accepted answer touches on it, some other answers go into even more detail. – deceze Sep 28 '17 at 10:42
  • @deceze Fair enough. Actually I have CVd a ton of questions as duplicates of that post, but haven't read the answers for a long time. – Teemu Sep 28 '17 at 10:48

0 Answers0