4. For Loops, Backwards



I cannot seem to understand the mechanism of how the array is reversed. Would someone please elaborate why we are making these changes in particular to get a reversed loop?

We need to make three changes to our for loop:

Edit the start condition to set the index equal to the length of the variable array minus one.

Then, set the stop condition to when the variable is greater than or equal to 0.

Finally, change index++ to index-- to subtract 1 from the iterator variable each loop.


lets say this is our array:


we can loop from left to right (which results in a, b, c, d) or from right to left (which results in d, c, b, a)

to achieve this, the starting index of the loop should be the the length of the array, the the condition which is index greater or equal to zero, and we need to decrease the index each time (given we go from higher to lower value)

but all this steps are given, you can just try to make the changes? If you need help with it, show me how far you got with making the suggested changes


I already made the changes and I got the correct output. I just don’t understand “why” we are doing this. Can you break down how the loop is iterating with these steps?


well, its useful to understand how to loop an array in reverse. Sometimes the exercise teaches a concept

i once needed a reverse loop over an array to remove widgets, so there are even practical uses to this concept.

Explanation of loop steps always sucks, i think its easiest to just see the values of index and the element by using a simple console.log:

console.log(index, arrayName[index])

where arrayName is the name of the array, just place this in the loop, then you can see the value of index and which element it loads, each step of the loop.


Just did that and understood what was happening,
Thanks a lot!


that is always a good trick, for testing purposes log/print additional information.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.