Start learning free

LESSON 124 OF 410 · WHILE LOOPS & FOR LOOPS

Reverse For Loop in JavaScript: Counting Backwards

Lesson Read the full explanation

A for loop can also count backwards, as long as we define the right conditions. For example:

for (let i = 7; i > 2; i--) {
	console.log(i);
}

The output of this code is:

7
6
5
4
3

Let's break down this code:

  • The initialization statement is let i = 7, so we start iterating from number 7.

  • We loop as long as i > 2, so we'll end at number 3. We could've written i >= 3 and it would still be correct.

  • The iteration statement is i--, so we decrease our number by 1 every time.


Assignment

Let's print all numbers from 5 through -5 in decreasing order.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check

    JAVASCRIPT · WHILE LOOPS & FOR LOOPS

    Looping In Reverse in JavaScript, explained

    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 = 7 runs once, before the first pass, and sets the start.
    • i > 2 is checked before every pass. As soon as it is false, the loop ends, so 2 is never printed.
    • i-- runs after every pass and lowers i by 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.

    1. Start at 5. The loop variable is i, so the start is let i = 5.
    2. Keep going while i >= -5. The last number to print is -5, so the condition has to be true when i is -5. With i > -5 the loop would stop one number early and -5 would be missing.
    3. Decrement with i--. Each pass moves one step down: 5, 4, 3, and on through 0 into the negatives.
    4. Print i inside the body with console.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 >=. Writing i <= -5 as the condition is false from the start when i begins at 5, so the loop body never runs.
    • Using i++ instead of i--. 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 > -5 stops at -4, while i >= -5 includes -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 then undefined. Start at arr.length - 1.

    Key takeaways

    • A reverse loop starts high, uses > or >= in the condition and decrements with i-- or i -= step.
    • To include the last value, use >= with that value. The exercise needs i >= -5.
    • To walk an array backwards, start at arr.length - 1 and stop after index 0.
    • toReversed() gives a reversed copy, while reverse() changes the array it is called on.
    Keep going with JavaScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free