0

I wrote a simple function to overwrite an array as follows:

function overwrite(arr) {
    let temp = [3, 2, 1];
    arr = temp;
}

let myarray = [1, 2, 3];
overwrite(myarray);
console.log(myarray);
[ 1, 2, 3 ]

The console output still shows the original array. How come?

By the way, I did figure out how to do it. I feel like the above approach should've worked but didn't, and so I am curious to know why.

Mr Wannabe
  • 143
  • 10

2 Answers2

3

You hand over an object reference of the array and you assign the array in local scope of overwrite.

To update the original array, you need to empty the array and splice the values.

function overwrite(arr) {
    let temp = [3, 2, 1];
    arr.splice(0, arr.length, ...temp);
}

let myarray = [1, 2, 3];
overwrite(myarray);

console.log(myarray);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • Aren't array's passed by reference? My thinking was with "arr = temp;" it updates arr reference with temp reference. Am I missing something? – Mr Wannabe Mar 12 '18 at 20:39
  • @MrCisco, in the scope of `overwrite`, you get an updated array, but the old reference is lost after assigning a new array. – Nina Scholz Mar 12 '18 at 20:42
  • Turns out you can't overwrite the reference in arr. I did end up using splice though (I should've been more clear in my post). – Mr Wannabe Mar 12 '18 at 23:43
0

Here is how it works behind the scene :

myarray contains the memory reference of [1, 2, 3], and for clarity, let's name it &myarray . Now when you pass myarray to the function overwrite(), the javascript engine assigns &myarray to arr (something like : arr = &myarray;). So, in this step you have something like this :

myarray = &myarray;
arr = &myarray;

And when you're assigning temp to arr, what you're basically doing is :

arr = &temp; // You're changing where arr point to, not myarray 

So myarray still points to &myarray (a reference to [1, 2, 3]) and arr points to &temp (a reference to [3, 2, 1]), and that's why the value is not changed.

And here is an illustration to visualize what I've explained :

enter image description here

CryptoBird
  • 508
  • 1
  • 5
  • 22