Reverse for Loop Javascript
In this article, you will learn how to use for loop in reverse order in javascript. You will look at their use case with multiple examples.
What is a for loop in javascript?
for loop is the most frequently used loop in JavaScript. If you know number of the iterations in advance then for loop is the best choice.
It can be used to repeat a block of code a given number of times or can also be used to iterate over an array, string, object, etc.
Generally, we loop from 0 to n or from the start to the end of an array. Like this:
Example: Loop moving forward
// forward for loop
for (let i = 0; i < 5; i++) {
console.log(i);
}
You can see the loop is moving forward from 0 to 4 but what if you want to loop in reverse order?🤔
Reverse for loop in javascript
The secret of moving forward or backward using in for loop lies in its definition.
For loop is defined as:
To reverse use the decrement step instead of the increment step.
You can see the increment/decrement part of the for loop. This is the part where you can change the direction of the loop.
If you want to loop in reverse order then you can use the decrement operator.
Note: Once you start using the decrement operator in for loop, you will also have to start from the end and have to change the condition.
Example 1: Reverse for loop in javascript
Let's print numbers from 5 to 1 using for loop (reverse order).
Example: Reverse for loop in javascript
// for loop backwards javascript
// print numbers from 5 to 1
for (let i = 5; i > 0; i--) {
console.log(i);
}
Here, we have started from 5 and have used the decrement operator. So, the loop will move backward from 5 to 1.
Example 2: Reverse for loop in array
Let's print elements of an array in reverse order using for loop.
Here, we will use the length property of an array to get the last index of the array, and then we will use the decrement operator to move backward.
Example: Reverse loop in array
// print elements of an array in reverse order
let arr = [10, 20, 30, 40, 50];
for (let i = arr.length - 1; i >= 0; i--) {
console.log(arr[i]);
}
Here, we have used the length property of an array to get the last index of the array, and then we have used the decrement operator to move backward.
Example 3: Reverse for loop in the string
Let's print characters of a string in reverse order using for loop.
Again, we will use the length property of a string to get the last index of the string and then decrease the index to move backward.
Example: Reverse loop in the string
// print characters of a string in reverse order
let str = "Hello";
for (let i = str.length - 1; i >= 0; i--) {
console.log(str[i]);
}
Here, we have used the length property of a string to get the last index of the string and then decreased the index to move backward.
This is all about for loop in reverse order in javascript. Hope you have learned something new today.
Happy coding!😊