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.
|
|
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:
|
|
This is only true for objects
Let’s look at a primitive parameter:
|
|
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.