micmath blog
RecentSimulating Pass By Reference in JavaScript
I've tried to clarify for myself something about how values are passed to functions in JavaScript, and it goes something like this:
- Variabless are always passed by value.
- Properties of objects act like references.
- Passing an object to a function passes the value of the object.
- The value of a reference acts like a reference to the same place in memory.
Okay, so how does this help us simulate pass-by-reference in JavaScript? Simple, if you want to pass a reference to a variable, you just need to make the variable a property of an object. Pass that object to teh function and you indirectly pass a reference to the variable.
This is especially useful when you want to write a function that works as a mutator -- a function that directly changes the variable that is passed to it.
Typically the pattern often used in JavaScript is that you pass the value of the variable, and the function returns a brand new value. This is really the only option if you are limited to pass-by-value. But, if you want to modify the variable passed in directly you must have pass-by-reference, and that's where this post is all leading up to.
var name = {ref: "Bob"}; // create a reference
function mutate(n) {
if (n.ref) n.ref += "-O!";
// no need to return anything, we changed the name directly
}
mutate(name);
alert(name.ref); // dereference
