Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading