Javascript objects in function parameters

I happily used javascript for a while not noting anything unique about function parameters. In most languages that I’ve worked with, function parameters are passed by value. Essentially, a copy of the variable is made and you can do whatever you want with it without worrying about messing up the original variable that’s stored safely away in the calling function.

However, it’s become evident that that isn’t always the case. Rather, sometimes, function parameters are passed by reference. This means that the calling function’s version of the variable will change as you change that variable in the callee function.

Here’s some code that shows you can change the contents of an object in a called function.

1
2
3
4
5
6
7
8
9
10
11
12
13
var myObject = {
count: 1
};
var doStuff = function(anObject) {
anObject.count++;
};
myObject.count === 1; // true
doStuff(myObject);
myObject.count === 2; // true

This was unexpected logically, but consistent with how I’ve experienced javascript. But, unfortunately, there’s more.

Only contents, not the entire object, can be changed

As Alnitak pointed out in a Stack Overflow answer, you can’t straight-up replace the object.

Here we see our original state is preserved:

1
2
3
4
5
6
7
8
9
10
11
12
13
var myObject = {
count: 1
};
var doCrazyStuff = function(anObject) {
anObject = null;
};
myObject.count === 1; // true
doCrazyStuff(myObject);
myObject.count === 1; // true

This is only true for objects

Let’s look at a primitive parameter:

1
2
3
4
5
6
7
8
9
10
11
var foo = 'bar';
var doBoringStuff = function(myVar) {
myVar = myVar + '!';
}
foo === 'bar' // true
doBoringStuff(foo);
foo === 'bar' // true

I don’t like really all of this, but I’m glad I have a solid understanding of how it works. If you’re going to be wanting to manipulate fields while working with the “conventional” understanding of “pass by value”, then I would recommend lodash’s clone and cloneDeep methods.

avatar

Dev Blog