1

I am reading about closures, and I found these small exercises that I solved by chance, but I don't understand why they work.

The exercise is :

for (var i = 0; i < 3; i++) {
  setTimeout(function log() {
    console.log(i); // What is logged?
  }, 1000);
}

I get that 3 will be printed 3 times because the value captured by log() when the for() ends.

Additionally, it was asked how to fix it for the console to print 0,1,2, and I found (by chance, to be honest), that it works by doing : for ( let i =0 ...

But I guess because Let is block scoped, but i don't really know how to explain it in simple words.

Not A Bot
  • 2,474
  • 2
  • 16
  • 33
notADevYet
  • 307
  • 2
  • 13
  • 1
    Does this answer your question: https://stackoverflow.com/a/11444416/12023402 ? – Aarni Joensuu Nov 17 '21 at 11:43
  • [This answer](https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var) puts it in simple terms. Scroll to the 'Hoisting' section. – Benlier Nov 17 '21 at 11:47

1 Answers1

1

The variables defined with let are blocked scope which means once you go out of the bracket it loses its value and if you try to access it will throw you an error. So, when the for is running the, i present in the console.log() will store the value for it like 0,1,etc.

whereas in the var part the var will be stored in memory and when the timeout is about to expire it will access the variable i in the memory and print whatever is there for that variable at that time.

innocent
  • 864
  • 6
  • 17
  • Thanks! that is a very easy way of putting it. Just one last question, if you don't mind. Why ```var`` logs ```3``` and not 2 ,since it should run 3 times . – notADevYet Nov 17 '21 at 11:55
  • 1
    It logs 3 because at the end of the for loop the condition should be false to terminate the loop so when it s value becomes 2 it goes back up and increases the value to 3 after which it checks condition in for loop which becomes false. So, it gets out of the loop. So, at end the variable accessed has value 3 – innocent Nov 17 '21 at 12:01
  • 1
    @notADevYet detailed [answer](https://javascript.plainenglish.io/5-tricky-javascript-problems-to-check-before-your-next-interview-part-1-60fdecaa59d6) why logs 3. – A1exandr Belan Nov 17 '21 at 12:21