How a reverse for loop works
A for loop has three parts in its parentheses: a starting statement, a condition and an update. A normal loop starts low and adds 1. A reverse loop (also called a backwards loop) flips all three: it starts high, keeps going while the variable is still above the stopping point, and subtracts 1 each time.
for (let i = 7; i > 2; i--) {
console.log(i);
}
This prints 7, 6, 5, 4 and 3, one per line. The parts work like this:
let i = 7runs once, before the first pass, and sets the start.i > 2is checked before every pass. As soon as it is false, the loop ends, so 2 is never printed.i--runs after every pass and lowersiby 1.
The condition i > 2 and the condition i >= 3 stop at the same place for whole numbers. Pick the one that matches how you think about the last value: "greater than 2" or "down to and including 3".
The exercise: print 5 down to -5
The task is to print every whole number from 5 down to -5, in decreasing order, with console.log. That is 11 numbers, and 0 is one of them.
- Start at 5. The loop variable is
i, so the start islet i = 5. - Keep going while
i >= -5. The last number to print is -5, so the condition has to be true wheniis -5. Withi > -5the loop would stop one number early and -5 would be missing. - Decrement with
i--. Each pass moves one step down: 5, 4, 3, and on through 0 into the negatives. - Print
iinside the body withconsole.log(i).
for (let i = 5; i >= -5; i--) {
console.log(i);
}
The output is 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, each on its own line. The loop passes through zero without any special handling, because 0 >= -5 is simply true.
Looping over an array backwards
The most common use of a reverse loop is visiting array elements from the last to the first. The last element sits at index length - 1 and the first at index 0, so the loop starts at arr.length - 1 and runs while i >= 0:
const arr = ['a', 'b', 'c'];
for (let i = arr.length - 1; i >= 0; i--) {
console.log(i, arr[i]);
}
2 c
1 b
0 a
Two details matter here. Starting at arr.length instead of arr.length - 1 reads past the end, where arr[i] is undefined. And the loop works for an empty array without any extra check: the start is -1, the condition is false immediately, and the body never runs.
Other ways to go through an array in reverse
If you only need the elements and not the indexes, you can reverse a copy and use for...of or forEach. toReversed() returns a new reversed array and leaves the original untouched:
const letters = ['x', 'y', 'z'];
for (const letter of letters.toReversed()) {
console.log(letter); // z, then y, then x
}
letters.toReversed().forEach(letter => console.log(letter));
console.log(letters); // [ 'x', 'y', 'z' ]
toReversed() is available in Node 20 and later and in current browsers. The older method reverse() reverses the array in place, which changes the original. To keep the original with reverse(), copy first: [...letters].reverse(). There is no built-in "reverse forEach", so a plain reverse for loop is often the simplest choice, especially when the loop needs the index or removes items while it goes.
Counting down by other steps
The update part does not have to be i--. Use i -= 5 to count down in fives:
for (let i = 10; i >= 0; i -= 5) {
console.log(i); // 10, 5, 0
}
Reversing a string or a number
Several searches for reverse loops are really about reversing a value. A reverse loop does this for a string, because s[i] reads one character:
const s = "hello";
let out = "";
for (let i = s.length - 1; i >= 0; i--) {
out += s[i];
}
console.log(out); // olleh
For a number, loop on its digits. n % 10 is the last digit, and Math.floor(n / 10) removes it:
let n = 12345;
let rev = 0;
while (n > 0) {
rev = rev * 10 + n % 10;
n = Math.floor(n / 10);
}
console.log(rev); // 54321
A shorter way is to turn the number into a string, reverse its characters and convert back: Number(String(12345).split("").reverse().join("")) gives 54321. This version also needs extra care for negative numbers, since the minus sign would end up at the wrong end.
Common mistakes
- Using the wrong comparison. A loop that counts down must use
>or>=. Writingi <= -5as the condition is false from the start whenibegins at 5, so the loop body never runs. - Using
i++instead ofi--. The variable then moves away from the stopping point, so the condition never becomes false. The loop runs forever (or until you stop it). When a loop seems stuck, check that the update moves toward the condition. - Off by one at the end.
i > -5stops at -4, whilei >= -5includes -5. Write the last value you want out on paper and test the condition against it. - Starting an array loop at
arr.length. The first value is thenundefined. Start atarr.length - 1.
Key takeaways
- A reverse loop starts high, uses
>or>=in the condition and decrements withi--ori -= step. - To include the last value, use
>=with that value. The exercise needsi >= -5. - To walk an array backwards, start at
arr.length - 1and stop after index0. toReversed()gives a reversed copy, whilereverse()changes the array it is called on.
