In JavaScript, all objects are stored and passed 'by reference'.
var a = { v: 'a' }, b = { v: 'b' };
a=b;
b.v='c';
a
and b
will reference the same object; a.v == 'c'
and b.v == 'c'
.
Primitive datatypes (string
, number
, boolean
, null
, and undefined
) are immutable; they are passed by value.
var a = 'a', b = 'b';
a=b;
b='c';
Since we're dealing with primitives, a == 'b'
and b == 'c'
.
Pedants will tell you that JavaScript isn't pass-by-reference in a classical sense, or that it's a "pure pass-by-value" language, but I think that complicates things for practical purposes. No, you can't directly modify an argument passed to a function as if it were a variable (which would be true if the language were true pass-by-reference), but you also don't receive a copy of an object passed as an argument (as you would if it were true pass-by-value). For most purposes (from the standpoint of the language's user, you), objects passed to a function are references, since you can modify that object and it affects the caller's object. See also the fantastic answers to this question.