Does JavaScript pass by reference? [duplicate]

Primitives are passed by value, and Objects are passed by “copy of a reference”.

Specifically, when you pass an object (or array) you are (invisibly) passing a reference to that object, and it is possible to modify the contents of that object, but if you attempt to overwrite the reference it will not affect the copy of the reference held by the caller – i.e. the reference itself is passed by value:

function replace(ref) {
    ref = {};           // this code does _not_ affect the object passed

function update(ref) {
    ref.key = 'newvalue';  // this code _does_ affect the _contents_ of the object

var a = { key: 'value' };
replace(a);  // a still has its original value - it's unmodfied
update(a);   // the _contents_ of 'a' are changed

Leave a Comment