0

It is my understanding that non-primitive types in JS are passed by reference not by value.

However, in the following code, when I log test.array_reference I am getting the initial value of test_array rather than a reference to the updated array that I expect

function tester() {
  let test_array = [];

  function change_array() {
    test_array = ["foo"];
  }

  return {
    array_reference: test_array,
    change_array: change_array
  };
}
test = tester();
test.change_array();
console.log(test.array_reference); // why is this the initial value and not a reference to the updated array

What am I missing? Are arrays not always passed by reference?

Occam
  • 519
  • 5
  • 18
  • The object contains a reference to the original array. Reassigning the variable doesn't change that. – Barmar Jan 30 '20 at 03:38
  • Use `test_array[0] = "foo";` to modify the array. – Barmar Jan 30 '20 at 03:39
  • Nothing is passed by reference. Objects are passed by (object) sharing. Modification to an object modifies the object (truth!), independently of variables that may evaluate to the object or assignments to such. See duplicate. – user2864740 Jan 30 '20 at 03:40
  • I see, I did not realize that I was not modifying the original array by assigning ["foo"] to it. Thanks for pointing me in the right direction @Barmar – Occam Jan 30 '20 at 04:29
  • If you're familiar with C-like languages, think of variables, array elements, and object properties all as pointers. You're reassigning the pointer, which doesn't affect other pointers that happened to point to the same memory. It's the difference between `ptr = new_val` and `*ptr = new_val`. – Barmar Jan 30 '20 at 16:24

0 Answers0