Skip to content
Advertisement

How is the third line of code here creating a reverse array?

This function should be taking an array and reversing its order. It works but I don’t understand what the third line “for (let i = arr.length…” is doing. Can someone please explain what is being pushed to the new reversed array?

const reverseArray = arr => {
    let reversed = [];
    for (let i = arr.length - 1; i >= 0; i--) {
        reversed.push(arr[i]);
    }
    return reversed
}

Advertisement

Answer

For the line:

for (let i = arr.length - 1; i >= 0; i--)

The for loop is starting at the last element, and looping through each until it gets to the end element. Each time it is then appending the array item to the reversed array.

As an example with an array:

Index Value
0     10
1     20
2     30
3     40

The first part of the for loop

let i = arr.length - 1

Sets i to arr.length – 1 = 4 – 1 = 3

So the first value added would be arr[3] = 40

Each iteration of the loop (while i is >- 0) assigns the current indexed i value and decrements i by 1.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement