In JavaScript, all objects are stored and transmitted "by reference."
var a = { v: 'a' }, b = { v: 'b' }; a=b; bv='c';
a
and b
will refer to the same object; av == 'c'
and bv == 'c'
.
Primitive data types ( string
, number
, boolean
, null
and undefined
) are immutable; they are passed by value.
var a = 'a', b = 'b'; a=b; b='c';
Since we are dealing with primitives, a == 'b'
and b == 'c'
.
Pedants will tell you that JavaScript is not a cross-reference in the classic sense, or that it is a “clean password”, but I think it complicates things for practical purposes. No, you cannot directly change the argument passed to the function as if it were a variable (which would be true if the language was true pass-by-reference), but you also do not get a copy of the passed object as an argument (as if it were was true pass-by-value). For most purposes (from the point of view of the user of the language, you), the objects passed to the function are references, since you can modify this object and influence the object of the caller. See also fantastic answers to this question .
source share