Reverse an Array in JavaScript using a For Loop
A breakdown of how to reverse an array of numbers using a for loop in JavaScript.
Lets take the array: [11, 5, 19, 98]
for example. We want the reverse: [98, 19, 5, 11]
1. Define the function and parameter for the array of numbers
function reverseArrayOfNumbers(arr){
*code body*
}
2. Create an empty array
This is to store the numbers in once they’ve been reversed
let reverseArray = [];
3. Create a for loop
for (let i = arr.length — 1 ; i >=0 ; i--){
*for loop code body*
}
Why i = arr.length — 1
?
i
will be our index when iterating through the array[11, 5, 19, 98]
has a length of 4 elements inside the array but indexes start from 0, so its index is 0, 1, 2, 3 — we minus 1 from the length to account for the fact array indexes start at 0
Why i > = 0
?
- whilst
i
is greater than or equal to 0 continue to run the loop! - there will be no element / number at index [-1], but there is one at index[0], so don’t need to go into negative numbers. stop at 0.
Why i — -
?
- This is a way of decrementing i on each iteration, if 3 is starting at 3, on iteration it will go: 3, 2, 1, 0. Remember our loop will not get to -1! (see above)
function reverseArrayOfNumbers(arr){
let reverseArray = [];
for (let i = arr.length — 1 ; i >=0 ; i--){
*for loop code body*
}
}
4. What happens inside the for loop
(array reminder: [11, 5, 19, 98]
)
let numberFromArray = arr[i]
reverseArray.push(numberFromArray)
On the first iteration i = 3
, so numberFromArray will be arr[3]
, which is 98! We then push this number into our empty array which now looks like this
reverseArray = [98]
That loop ran successfully, we now minus 1 from i
and start again.
— — — — — — — — — — — — — — — — — — — — — — — — —
Second iteration: i = 2
, so numberFromArray will be arr[2]
, which is 19! We then push this number into our empty array which now looks like this
reverseArray = [98, 19]
— — — — — — — — — — — — — — — — — — — — — — — — —
That loop ran successfully, we now minus 1 from i
and start again.
Third iteration: i = 1
, so numberFromArray will be arr[1]
, which is 5! We then push this number into our empty array which now looks like this
reverseArray = [98, 19, 5]
— — — — — — — — — — — — — — — — — — — — — — — — —
That loop ran successfully, we now minus 1 from i
and start again.
Fourth iteration: i = 0
, so numberFromArray will be arr[0]
, which is 11! We then push this number into our empty array which now looks like this
reverseArray = [98, 19, 5, 11]
— — — — — — — — — — — — — — — — — — — — — — — — —
We have reversed our original array!
The fifth iteration would see i = -1,
but -1 is not greater than 0, nor is it equal to 0, so the loop is terminated.
Final code:
function reverseArrayOfNumbers(arr){
let reverseArray = [];
for (let i = arr.length — 1 ; i >= 0 ; i--){
let numberFromArray = arr[i]
reverseArray.push(numberFromArray);
}
return reverseArray
}
Don’t forget to call your function at the end!
Happy coding / reversing.