0

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

7
  • How did you come to realize the item variable is only set once? It's inside the for loop. Commented Feb 21, 2022 at 22:12
  • it's in the first part of the for, where code only runs at start of the loop Commented Feb 21, 2022 at 22:15
  • Did you look up what the 3 expressions within the parentheses are, and when they are executed? It is well documented and should explain the behavior. Commented Feb 21, 2022 at 22:17
  • yes, it clearly says there that the 'final-statement' runs on each iteration, so my assignment should work Commented Feb 21, 2022 at 22:21
  • 1
    @Alex No, it says "An expression to be evaluated at the end of each loop iteration". First it will evaluate the initialization, then the condition, then the statement then the final-expression. So during the statement of the first iteration, the final-expression will not have been evaluated yet and thus item wont have a value. Commented Feb 21, 2022 at 22:24

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

A reverse for loop may in fact execute quicker and consume less memory than the reverse().forEach() chain! But please take that with a grain of salt: if it takes 50 times as long to do it 'my way' as the 'efficient way' that seems like a big gain. But if it only take 10 milliseconds to do it 'my way' then isn't that fast enough? In other words: Premature optimization wastes time and effort. You can solve your problem quickly and easily and then only refactor for efficiency if performance is unacceptable.
Another nugget of coder wisdom I can share is "Major performance gains are algorithmic." The algorithmic complexity of handling your "loop that runs in another big loop" is going to be geometric - the size of the first loop times the size of the second loop. Real efficiency would come from processing less data, or handling multiple streams in parallel (web workers). Micro optimizations at the micro-second level are not ideal. The SLOWEST option, Reduce, takes 0.2microseconds to execute in those benchmarks. Food for thought!
I'm using Firefox and Reduce is slower than everything but for...of, so yeah, it's up to the browser and a lot of other variables. The slowest one can do over 600k operations/sec, so unless you have several million list items, this particular method isn't likely the bottleneck. Algorithms : Methods :: Strategies : Tactics

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.