1

If I mutate the value of myArray within myFunction, the new myArray is updated:

let myArray = [1, 2, 3];
console.log( JSON.stringify(myArray) ); // [1, 2, 3]

function myFunction(arr) {
  arr.push(4);
  console.log( JSON.stringify(arr) ); // [1, 2, 3, 4]
  return arr;
}

myFunction(myArray);
console.log( JSON.stringify(myArray) ); // [1, 2, 3, 4]
.as-console-wrapper {max-height: 100% !important;top: 0;}
.as-console-row::after {display: none !important;}

However, if I try to reassign myArray with arr = [0]; within myFunction, myArray stays the same.

let myArray = [1, 2, 3];
console.log( JSON.stringify(myArray) );; // [1, 2, 3]

function myFunction(arr) {
  arr = [0];
  console.log( JSON.stringify(arr) ); // [0]
  return arr;
}

myFunction(myArray);
console.log( JSON.stringify(myArray) ); // [1, 2, 3]
.as-console-wrapper {max-height: 100% !important;top: 0;}
.as-console-row::after {display: none !important;}

Why can't myArray be reassigned in the example above, but can be if I do this:

let myArray = [1, 2, 3];
myArray = [0];
console.log(myArray); // [0]
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
  • Quoting Wiki's ["call by sharing"](https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing) section: _Mutations of arguments performed by the called routine will be visible to the caller [but] it is not possible to simulate an assignment on that variable in the callee's scope_. – sp00m Jun 21 '22 at 13:59
  • 2
    JavaScript does not have "pass by reference" so the parameter `arr` is a different variable than the variable `myArray`, so assigning something `arr` does not affect `myArray`. `arr` holds a reference/pointer/linkage to the array and that one is passed by value, so `arr` and `myArray` point to the same object. – t.niese Jun 21 '22 at 14:04

2 Answers2

0

you are confusing the addressing linked to the internal elements of the array with the addressing of the array itself

let myArray = [1, 2, 3];  

create in memory an array object with [1, 2, 3]
and give his address on myArray variable

function myFunction(arr)

create a new variable named arr
with a copy of the address of myArray variable



in the same way you have:

let myArray = [1, 2, 3]
let arr     = myArray

arr = [0]
 
console.log( JSON.stringify(myArray) ) // [1, 2, 3]
console.log( JSON.stringify(arr) )     // [0] 
.as-console-wrapper {max-height: 100% !important;top: 0;}
.as-console-row::after {display: none !important;}
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
-1

In your example you're not actually reassigning myArray. You'd need to do myArray = myFunction(myArray).

Scott
  • 232
  • 1
  • 10
  • The OP assumes that `myArray` is passed by reference (which it is not), and if that would be the case then `arr` would just be a reference to `myArray`, so assigning to `arr` would also change `myArray`. That's a misconception that happens quite often. – t.niese Jun 21 '22 at 14:08