Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

223
Views
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
}
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

If you are new to Javascript or programming in general, check this cool website: W3Schools

What the 3rd line does is to go from the last element of an array (hence the arr.length - 1, the -1 is because array positions start on 0 not 1) to the first one, it pushes each value to a new array (reversed) and that's how you get the final result.

about 4 years ago · Juan Pablo Isaza Report

0

 ex - arr[a,b,c,d,e,f,g]
          0 1 2 3 4 5 6

this loop is currently worked as reverse like (6,5,4,3,2,1,0) because it's consist i--

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

when loop runs the last element of arr array in insert first of reversed array

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!