If JavaScript passes a function argument as a reference on the original object, why can´t I modify the original array with this simple function?
var array1 = ["one"];
function change(array) {
var array2 = ["222"];
array = array2;
}
change(array1);
console.log(array1); // this prints ["one"] instead of ["222"]
Why sometimes objects seem to be passed as reference and in this case it´s passed as a copy?
Because the parameter array isn't the same as array1. They are separate variables. Note that variables are pass-by-value, for objects it's passing a copy of the reference by value. So you would need to do:
var array1 = ["one"];
array1 = change(array1);
function change(array) {
var array2 = ["222"];
array = array2;
return array;
}
console.log(array1);
Why sometimes objects seem to be passed as reference and in this case it´s passed as a copy?
It's not passed as a copy of the array, it's passed as a copy of the reference to the array. There is still only one array, and you can change the array in the function using that reference:
var array1 = ["one"];
function change(array) {
array[0] = "222";
}
change(array1);
console.log(array1); // this prints ["222"]
What you can't do is to replace the array with a different array in the function. If you assign a new array to the parameter then it will point to the new array, but the variable array1 is still unchanged and points to the original array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With