Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

           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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading