javascript pass object as reference

In JavaScript objects are always passed by copy-reference. I’m not sure if that’s the exactly correct terminology, but a copy of the reference to the object will be passed in.

This means that any changes made to the object will be visible to you after the function is done executing.

Code:

var obj = {
  a: "hello"
};

function modify(o) {
  o.a += " world";
}

modify(obj);
console.log(obj.a); //prints "hello world"

Having said that, since it’s only a copy of the reference that’s passed in, if you re-assign the object inside of your function, this will not be visible outside of the function since it was only a copy of the reference you changed.

Code:

var obj = {
  a: "hello"
};

function modify(o) {
  o = {
    a: "hello world"
  };
}

modify(obj);
console.log(obj.a); //prints just "hello"

Leave a Comment