It's unfortunate that the phrase by reference gets thrown around like it does, because it has a perfectly clear meaning that is completely different from one the being (mis-) used here. All values in JavaScript are copied/passed by value. When dealing with objects, that value is a reference to the object. But it's still a value that is copied.
When you make a shallow copy of an array using slice
, the elements that are references to objects have those same references copied to the new array. That is, the same position in both arrays will refer to the same object. So, yes, changing one changes the other because there is no other; they are the same object.
Proof:
var arr = [[7, 6, 5], 4, 5];
var copy = arr.slice();
arr[0][0] = 88;
console.log(copy[0][0]); // 88
Tangent on pass-by-reference
If you can't write a function like this:
function swap(arg1, arg2) {
var temp = arg1;
arg1 = arg2;
arg2 = temp;
}
...that actually swaps the values of two variables:
var one = [1, 2, 3];
var two = ["a", "b", "c"];
swap(one, two);
console.log(one) // same as before
...then your language does not support pass by reference.
More pass-by-value
Wait, doesn't the following demonstrate that JavaScript must be pass-by-reference:
function Test(arg1) {
this.arg = arg1;
}
var one = [1, 2, 3];
var x = new Test(one);
x.arg[0] = 5;
console.log(one); // it's been updated!
No! If you think this then you still haven't understood what pass by reference actually is. Yes, a reference to the original array was passed to Test
, but it was passed by value. In other words, x.arg
refers to the same object in memory as one
but it is not an alias for one
. To prove this, you simply need to assign something new to x.arg
:
x.arg = ["new array"];
This does not affect one
. These two variables are independent. JavaScript is strictly pass-by-value. There are no exceptions.