Kevin Powell - CommunityKP-C
Kevin Powell - Communityβ€’5mo agoβ€’
7 replies
brr

Closures: var vs let

for (var i = 0; i < 3; i++) {
  const log = () => {
    console.log(i);
  };
setTimeout(log, 100)
}; // 4, 3, 3, 3

for (let i = 0; i < 3; i++) {
  const log = () => {
    console.log(i);
  };
setTimeout(log, 100)
}; // 0, 1, 2

Link: https://www.youtube.com/watch?v=vKJpN5FAeF4&t=19s

I do understand that during 100 milliseconds timeout, it evaluates the value of i by running complete for loop. But, I am confused if the closure variable is in heap, why is it unaffected?
Was this page helpful?