Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

191
Views
question about scope, closures and Let variables

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!