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
}
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.
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
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.