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

247
Views
Variable assignments in negative for loop

A typical reverse for loop:

           for(let i = arr.length - 1, item = arr[i]; i >= 0; i--){
              let item = arr[i];
              do thing with item
            }
   

I was thinking I could remove the brackets by assigning the item variable in the for declaration

           for(let i = arr.length - 1, item = arr[i]; i >= 0; i--)
              do thing with item
   

But it doesn't work and I didn't understand why. Then after some careful look at the code, I realised that the item variable is set only once. So I changed it to

           for(let item, i = arr.length - 1; i >= 0; i--, item = arr[i])
              do thing with item

But now item appears undefined and can't figure out why because the code appears correct

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

0

You aren't assigning an initial value to item. These are not "typical" for loops, but I wouldn't use a loop anyway.

You just want the values of an array, so you can use Array functions:

arr.forEach((item, index) => { 
  // do something with item
}

If you want to handle them in reverse order, there is a reverse function that you can use to flip the ends:

arr.reverse().forEach(() => {})

If you wanted to modify the array, for example by doubling the values in an array of numbers, you can use the map method which functions similarly but it returns values that become an output array.

const doubledArr = arr.map((item) => { return item * 2 });

And a streamlined, reversed doubling:

const doubledReversedArr = arr.map(x => 2*x);

Same effect, less code.

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!