I'm facing an issue with manipulating arrays in JavaScript within a function. This problem arises from an exercise found in the book Eloquent JavaScript, focusing on two specific functions:
reverseArray()
: designed to produce a new array that is the reverse of the original input array.reverseArrayInPlace()
: meant to reverse the original input array without creating a new one.
While attempting to implement the logic for reverseArrayInPlace()
, I tried calling reverseArray()
and reassigning its result back to the argument array. However, upon displaying the modified array, no changes were reflected. This was puzzling to me as I expected JavaScript arrays to be passed by reference.
Furthermore, I experimented with reassigning an array variable to another array successfully outside any function context. So, what could possibly be causing this discrepancy? It's worth mentioning that the exercise explicitly prohibits the use of the built-in reverse()
method in JavaScript.
function reverseArray(array) {
var new_array = [];
for (var i = array.length-1; i >= 0; i--)
new_array.push(array[i]);
return new_array;
}
function reverseArrayInPlace(array) {
array = reverseArray(array);
}
var r1 = [1,2,3,4,5,6,7,8,9,10];
console.log("r1 ", r1.join(","));
// → 1,2,3,4,5,6,7,8,9,10
console.log("reverse of r1 ", reverseArray(r1).join(","));
// → 10,9,8,7,6,5,4,3,2,1
console.log("r1 ", r1.join(","));
// → 1,2,3,4,5,6,7,8,9,10
reverseArrayInPlace(r1);
// the changes are not reflected here
console.log("r1 reversed in place ", r1.join(","));
// → still 1,2,3,4,5,6,7,8,9,10;
// this should display r1 = 10,9,8,7,6,5,4,3,2,1