Home > Software design >  Variable assignments in negative for loop
Variable assignments in negative for loop

Time:02-22

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

CodePudding user response:

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.

  • Related