Currently, I am delving into my Javascript book and attempting to master the art of reversing an array by creating a custom reverse function. My challenge is to flip the array without resorting to creating a new variable for storage. After what seemed like finding the solution, running output tests in two different ways (refer below) resulted in contrasting results:
function reverseArrayInPlace(array) {
for (var i = 0; i < array.length; i += 1) {
array = array.slice(0, i).concat(array.pop()).concat(array.slice(i));
}
console.log(array);
}
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
The outputs are as follows:
reverseArrayInPlace(array);
console.log(array);
> [ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 ]
> [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
Interestingly, I realize that utilizing console.log()
inside the function returns the intended result.
However, when I utilize console.log()
outside the function, it inexplicably causes the original array configuration with the last element omitted. An explanation regarding this peculiar behavior would be greatly appreciated.