I'm reading through Eloquent Javascript and facing one of the exercises, I found a rather odd behavior. (at least for me)
the exercise asks to create a function in order to reverse an array. I thought I could loop over the array and each time pop one item from the original array and push it into a temporary array that is going to finally be returned. but as I'm looping over the array either with a for-of loop or typical sequential loop, last item is not transferred.
can someone tell me what happens exactly?
const reverseArray = function(array) {
let rev = [];
for (let x = 0; x <= array.length; x++) {
rev.push(array.pop());
console.log(rev, array)
}
return rev;
};
console.log(reverseArray(["A", "B", "C"]));
output:
["C"] ["A", "B"]
["C", "B"] ["A"]
["C", "B"]