Code highlights logo

Learn

Loops

Looping in Reverse

To loop in reverse, we can leverage the power of the for loop and utilize its conditional statement. Typically, the for loop is used to iterate forward, increasing the loop variable on each iteration. However, by modifying the loop's initialization, condition, and update expressions, we can achieve reverse iteration.

1for (let i = endValue; i >= startValue; i--) {
2 // loop body
3}

In this example, endValue represents the starting point of the reverse iteration, and startValue represents the endpoint. By setting i to endValue as the initial value of the loop variable, we ensure that the loop starts from the end. The condition i >= startValue ensures that the loop continues as long as i is greater than or equal to the startValue. Finally, the i-- update expression decreases the value of i on each iteration, allowing us to move towards the startValue in reverse.

Example: Printing Numbers in Reverse

Let's see a practical example of looping in reverse. Suppose we want to print the numbers from 10 to 1 in descending order.

1for (let i = 10; i >= 1; i--) {
2 console.log(i);
3}

Output:

110
29
38
47
56
65
74
83
92
101

In this example, the loop starts from 10 (endValue), continues until 1 (startValue), and decreases by 1 on each iteration. By printing the value of i inside the loop, we achieve the desired result of reversing the order and printing the numbers in descending order.


Instructions

1.

Modify the for loop to start at 10 and loop down to 0.

Sign up to start coding

Already have an account?

Sign In

Course content