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

253
Views
Unable to figure out the output of simple javascript code

function func2() {
  for (let i = 0; i < 3; i++) {
    setTimeout(() => console.log(i), 2000);
  }
}

func2();

Due to closure, the console.log statement should remember its outer lexical environment, which is first setTimeout and then the for loop. Since i is not available in the setTimeout context, it looks in the execution context of the for loop, and searches for the value of i there.

Now, that value, after 2 seconds, should have been 3 for all three executions of console.log. But it displays the output as:

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

0

You have used let which is block scoped so there will be separate i for each for loop iteration.

1) If you want to output consective 3 so you can declare i outside of for-loop, then there will be only single i with the value 3.

function func2() {
  let i;
  for (i = 0; i < 3; i++) {
    setTimeout(() => console.log(i), 2000);
  }
}

func2();

2) If you want same lexical scope then you can also use var here,

var is function scoped, So there will only be one i

function func2() {
  for (var i = 0; i < 3; i++) {
    setTimeout(() => console.log(i), 2000);
  }
}

func2();

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!