Reading Assignment – Objects and Arrays

Can someone please explain me this… In eloquentJS exercises there is one called Reversing an Array and the solution for the first function is written like this:

function reverseArray(array) {
let output = [];
for (let i = array.length - 1; i >= 0; i–) {
output.push(array[i]);
}
return output;
}

Before seeing that I wrote:

function reverseArray (array) {
let newArray = [];
for (let value of array) newArray.unshift(value);
return newArray
}

I got the correct solution when trying my code but got disappointed when I saw what the correct answer in the book was… I understand the solution in the book, just don’t understand if there is an obvious reason why it should be written like that, something that I obviously can’t see on my own… Thank you for your help in making me better understand programming.

The first solution is written with simple for loop but that does not mean yours is incorrect. May the book is trying to show how for loop work. And any question can have multiple solutions, it all about what you prefer to use.

1 Like