Skip to content

Instantly share code, notes, and snippets.

@luislee818
Last active August 29, 2015 14:01
Show Gist options
  • Save luislee818/76a00ff1094d31f2106a to your computer and use it in GitHub Desktop.
Save luislee818/76a00ff1094d31f2106a to your computer and use it in GitHub Desktop.
JavaScript function call is pass by value (and passed reference by value).
var foo, changeProperty, changeParam;
foo = {
bar: 123
};
changeProperty = function (obj) {
obj.bar = 999;
};
changeParam = function (obj) {
obj = undefined;
};
console.log(foo.bar); // 123
changeProperty(foo);
console.log(foo.bar); // 999
changeParam(foo);
console.log(foo); // { bar: 999 }

It is always pass by value. Period. A reference to the object is passed by value to the function. That's not passing by reference. "Pass by reference" could almost be thought of as passing the variable itself, rather than its value; any changes the function makes to the argument (including replacing it with a different object entirely!) would be reflected in the caller. That last bit isn't possible in JS, because JS does not pass by reference -- it passes references by value. The distinction is subtle, but rather important to understanding its limitations.

http://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language#comment13629879_518111

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment