The real problem here is that you're not mutating anything; you're just reassigning the variable z
in the function. It wouldn't make a difference if you passed an object or array.
var x = ['test'];
var y = function(z) {
z=['foo'];
return z;
}
y(x);
x; // Still ['test']
Now, what others have said is also true. Primitives cannot be mutated. This is actually more interesting than it sounds, because the following code works:
> var x = 1;
> x.foo = 'bar';
"bar"
> x
1
> x.foo
undefined
Notice how the assignment to x.foo
was seemingly successful, yet x.foo
is nowhere to be found. That's because JavaScript readily coerces primitive types and object types (there are "object" versions of primitives, that are normal objects). In this case, the primitive 1
is being coerced into a new object (new Number(1)
), whose foo
attribute is getting set, and then it is promptly destroyed, so no lasting effects occur.