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

179
Views
Difference between var and let in for loop

for(var i = 0; i < 5; i++){
  setTimeout(() => console.log(i)
}

    for(let i = 0; i < 5; i++){
      setTimeout(() => console.log(i)
    }

Why the loop with let return 0,1,2,3,4 but loop with var return 5,5,5,5,5 ?

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

0

This is because of hoisting. Declaring a variable with var in your for loop doesn’t limit its scope to just that block of code like it would using let. Since its existence extends beyond that for loop, when the value is evaluated by the setTimeout() callback, you get the last value it was set to. (it gets set to 5, which is why the for loop stops)

for (var val = 0; val < 5; val++) {
  setTimeout(() => console.log(i)
}
if (val === 5) {
  console.log('I can still see the value');
}

You can see the same behavior while using let if you’ve already declared the variable before using it in your for loop.

let i;
for (i = 0; i < 5; i++) {
  setTimeout(() => console.log(i)
}

Now it would behave the same way as the var for loop did.

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!