Skip to content

Instantly share code, notes, and snippets.

@c4urself
Last active December 10, 2015 19:58
Show Gist options
  • Save c4urself/4485335 to your computer and use it in GitHub Desktop.
Save c4urself/4485335 to your computer and use it in GitHub Desktop.
Javascript (mainly) pass-by-value
// More explicit example of
// http://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language
//
// When you change the `item` property of the object referenced by `obj1`, you are changing the value
// of the `item` property that was originally set to 'unchanged'. When you assign `obj2` a value of
// {item: 'changed'} you are changing the reference to a new object. This object immediately goes out
// of scope when the function exits.
function changeStuff(_num, _obj1, _obj2) {
_num = _num * 10;
_obj1.item = 'changed';
_obj2 = {item: 'changed'};
}
var num = 10,
obj1 = {},
obj2 = {};
obj1.item = 'unchanged';
obj2.item = 'unchanged';
changeStuff(num, obj1, obj2);
console.log(num); // 10
console.log(obj1.item); // "changed"
console.log(obj2.item); // "unchanged"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment