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
In closures we know for each loop iteration variable "i" is a fresh copy, then why const "i" not work in a loop

/this code works and each callback is referencing to a different "i" it indicates that for each loop iteration a new copy of "i" is created, due to that the callback forms a closure with a distinct "i" each time/

const arr = [10, 12, 15, 21];
for (let i = 0; i < arr.length; i++) {
  setTimeout(function() {
  console.log('Index: ' + i + ', element: '+ arr[i]);
  }, 3000)
}

/This gives error: Assignment to constant variable. Why not in this case a new constant "i" is created for each loop iteration/

const arr = [10, 12, 15, 21];
for (const i = 0; i < arr.length; i++) {
  setTimeout(function() {
    console.log('Index: ' + i + ', element: '+ arr[i]);
  }, 3000)
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

++i doesn't modify the instance of i - it creates a new instance with an incremented value and assigns it back to i. If i is defined as a const, you cannot assign the value back to it, and hence the error.

about 4 years ago · Juan Pablo Isaza Report

0

Because a constant must not be changed, you can't i++ on a constant.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const

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!