Search code examples
javascriptarraysobject

How does reassigning non-primitives in functions work (Javascript)?


How does passing by reference work when reassigning non-primitives in functions? When considering address'.

for example:

var a = [9]; //suppose this is stores at 0x01

function changeto5(array){ 
array = [5]; 
}

function(a);//passes the address 0x01
console.log(a) //outputs [9]

shouldn't the value at the memory address 0x01 be updated to [5], i'm very confused on why this does not happen. My current understanding of this, is that at the address 0x01 the value of [9] is stored, and a new address e.g 0x02 is used to store [5]. But this would mean there is no way to change the value stored at 0x01 unless done in the same scope and it seems inconsistent, as you can change the elements of the array in the function. Is my current understanding correct?


Solution

  • You are replacing the array in the function, which will only affect the array in the function's scope. The array outside the function still remains the same.

    This is because non-primitives are not really passed by reference - the reference is instead copied, so under the hood, modifying the contents of the parameter will persist, but overwriting the "reference" won't affect the original.

    Thus, if you reference the array, you will see the expected output:

    var a = [9]; //suppose this is stores at 0x01
    
    function changeto5(array){ 
      array[0] = 5
    }
    
    changeto5(a);//passes the address 0x01
    console.log(a) //outputs [5]