Let i = arr.length - 1; i >= 0

As stupid as it may sound, someone can explain me why (let i = arr.length -1; i >= 0; …) in the code below? I need to understand to move on. It might be the sleepless night but I am stuck on this one.

const reverseArray = arr => {
let reversed = ;
for (let i = arr.length - 1; i >= 0; i–) {
reversed.push(arr[i]);
}
return reversed
}
const sentence = [‘sense.’,‘make’, ‘all’, ‘will’, ‘This’];

console.log(reverseArray(sentence));

So the purpose of this function is to reverse any array passed into it. Therefore the best way to do that is to start at the last element, add that to a new array and then work your way back, since push() adds the element to the end of an array. So how can you start at the end of an array? Well, we know that arrays are 0-indexed, meaning that the first element has an index of 0, the second has an index of 1 etc. We also know that .length returns the absolute size of an array. So lets use an example array to demonstrate this.

const arr = [0, 1, 2, 3]; console.log("Array Length: ", arr.length); // This will print 4 console.log("Last Element: ", arr[3]) // This will print 3

The size of this array is 4, but the last element is accessed using index 3, since indexes start from 0. Returning to your example, we know we want to start from the end of the array. However since we can see that arr.length will return a number 1 bigger than the index of the last element, we need to first subtract 1 from it. Therefore for this example, i would initialise to arr.length-1 = 4-1 = 3, and thus get the last element correctly. Then, since we are working back the way we need to use i-- to ensure we go in the correct direction. And finally we need to make sure that the loop stops when it reaches the end (well, in this case start) of the array. We know indexes start at 0, therefore i >= 0 ensures the loop runs when i=0, and then stops.

Hopefully that helps, let me know if you have any other questions!

1 Like

Thank you soooooooooooooo much. I got it now. These simple things have a way to trick me and when I see the answer I feel a bit frustrated I confess. Thank you once more, I really appreciate it.

1 Like