I have a problem with arrays in JavaScript and manipulating them inside a function.
This is an exercise from the book Eloquent JavaScript. It is about two functions:
reverseArray(): returns a new array which is the reverse of the argument array.reverseArrayInPlace(): just reverses the argument array itself.
Inside reverseArrayInPlace(), I just called reverseArray() to create a new array and reassign to the argument of reverserArrayInPlace(). However, when I get to display the passed array, the reassignment is not reflected to the array passed.
I thought arrays in JavaScript are always passed by reference?
I have also tried to reassign an array variable to another array and it was successful if done outside a function. What could be the problem?
By the way, the exercise forbids the use of the 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
reverseArrayreturns a new array ...array = reverseArray(array);assigns the local (the argument) reference to the array to this new array, thereby breaking the reference to the passed in array, but does not change the passed in array, because, well, it doesn'tpass-by-value a reference to an object:p