JavaScript Pass Object as Reference

javascript pass object as reference

In JavaScript objects are always passed by copy-reference. I'm not sure if that's the exactly correct terminology, but a copy of the reference to the object will be passed in.

This means that any changes made to the object will be visible to you after the function is done executing.

Code:

var obj = {  a: "hello"};
function modify(o) { o.a += " world";}
modify(obj);console.log(obj.a); //prints "hello world"

Pass-by-reference JavaScript objects

When you assign one variable to another, it's not that both those variables are now linked by reference; you're misunderstanding what "pass by reference" means here.

A variable holding an object does not "directly" hold an object. What it holds is a reference to an object. When you assign that reference from one variable to another, you're making a copy of that reference. Now both variables hold a reference to an object. Modifying the object through that reference changes it for both variables holding a reference to that object.

When you assign a new value to one of the variables, you're just modifying the value that variable holds. The variable now ceases to hold a reference to the object, and instead holds something else. The other variable still holds its reference to the original object, the assignment didn't influence it at all.

Does JavaScript pass by reference?

Primitives are passed by value, and Objects are passed by "copy of a reference".

Specifically, when you pass an object (or array) you are (invisibly) passing a reference to that object, and it is possible to modify the contents of that object, but if you attempt to overwrite the reference it will not affect the copy of the reference held by the caller - i.e. the reference itself is passed by value:

function replace(ref) {
ref = {}; // this code does _not_ affect the object passed
}

function update(ref) {
ref.key = 'newvalue'; // this code _does_ affect the _contents_ of the object
}

var a = { key: 'value' };
replace(a); // a still has its original value - it's unmodfied
update(a); // the _contents_ of 'a' are changed

JS passing the whole object to a function takes more memory

It has to load the whole foo object into the function’s scope to access the b property, which increases the memory consumption.

This is just wrong. As you said

the object is passed by reference.

Thus in both cases a reference gets passed, which will consume the same memory (if it does at all).

The advice in the book is to always pass only what you need instead

That makes sense as a good practice for clean design.

Pass object into function as parameter in Javascript

Yes. In javascript, objects are passed by reference. So, if you change the value of an object within the function, it changes it back outside of the function.

If you did something like this, though, it wouldn't be the case:

function setWhite(obj){
obj = {
color: "white",
size: "M"
}
}

var shirt = {
color: "red",
size: "L"
}

setWhite(shirt);

console.log(shirt); // shirt will remain red / L

Note the difference is that I'm reassigning obj inside the setWhite() method, so the original obj is lost to that function.

This is an important concept to understand, since it can have disturbing and unintended consequences if you let it slip your mind, accidentally changing the value on objects that you didn't want to change, just temporarily manipulate the data for some other purpose. It's especially important to keep in mind when you start working with async functions. Async functions happen in the background, and you have to specify when to 'await' for them. If you call an async function expecting it to change your objects values, but don't await it, your object might not have the updated values yet when you go to use them later in the code that calls the async function.

Similarly, if you call an async function, but don't await it, and later change the object that was passed in, by the time the async function goes to use the values from that object, they could be different than you intended when you called it.

Pass variables by reference in JavaScript

There is no "pass by reference" available in JavaScript. You can pass an object (which is to say, you can pass-by-value a reference to an object) and then have a function modify the object contents:

function alterObject(obj) {
obj.foo = "goodbye";
}

var myObj = { foo: "hello world" };

alterObject(myObj);

alert(myObj.foo); // "goodbye" instead of "hello world"

You can iterate over the properties of an array with a numeric index and modify each cell of the array, if you want.

var arr = [1, 2, 3];

for (var i = 0; i < arr.length; i++) {
arr[i] = arr[i] + 1;
}

It's important to note that "pass-by-reference" is a very specific term. It does not mean simply that it's possible to pass a reference to a modifiable object. Instead, it means that it's possible to pass a simple variable in such a way as to allow a function to modify that value in the calling context. So:

 function swap(a, b) {
var tmp = a;
a = b;
b = tmp; //assign tmp to b
}

var x = 1, y = 2;
swap(x, y);

alert("x is " + x + ", y is " + y); // "x is 1, y is 2"

In a language like C++, it's possible to do that because that language does (sort-of) have pass-by-reference.

edit — this recently (March 2015) blew up on Reddit again over a blog post similar to mine mentioned below, though in this case about Java. It occurred to me while reading the back-and-forth in the Reddit comments that a big part of the confusion stems from the unfortunate collision involving the word "reference". The terminology "pass by reference" and "pass by value" predates the concept of having "objects" to work with in programming languages. It's really not about objects at all; it's about function parameters, and specifically how function parameters are "connected" (or not) to the calling environment. In particular, note that in a true pass-by-reference language — one that does involve objects — one would still have the ability to modify object contents, and it would look pretty much exactly like it does in JavaScript. However, one would also be able to modify the object reference in the calling environment, and that's the key thing that you can't do in JavaScript. A pass-by-reference language would pass not the reference itself, but a reference to the reference.

edit — here is a blog post on the topic. (Note the comment to that post that explains that C++ doesn't really have pass-by-reference. That is true. What C++ does have, however, is the ability to create references to plain variables, either explicitly at the point of function invocation to create a pointer, or implicitly when calling functions whose argument type signature calls for that to be done. Those are the key things JavaScript doesn't support.)

Pass object and properties by reference in Javascript

Originally, this is what I was trying

You're not passing an object with its properties there. You're passing the value of a single property, and assignments to multiplier do indeed just overwrite the local variable in the function. You need to pass an object and explicitly assign to its property:

function incMultiplier(valueObj) {
var numOfKeys = Object.keys(multipliers).length;
if (valueObj.multiplier !== numOfKeys) {
valueObj.multiplier++;
} else {
valueObj.multiplier = 1
}
}

incMultiplier(shapesMovements[index].rotation.x)
incMultiplier(shapesMovements[index].position.x)
incMultiplier(shapesMovements[index].rotation.y)
incMultiplier(shapesMovements[index].rotation.z)

It's not necessary to pass the whole shapesMovements objects and everything nested within them, passing a single mutable object is enough.

Does .bind(this) pass by reference or by value?

So if I change the parameters of the this object a bit later in the
outer block of code, and afterwards call foo, will foo use the value
of this at the time I called bind, or at the time I called foo?

at the time you called foo.

this is a reference to Object. That means Object may get mutated at some point and you will get "fresh - up to date" values of it.

JavaScript: How to pass object by value?

Not really.

Depending on what you actually need, one possibility may be to set o as the prototype of a new object.

var o = {};
(function(x){
var obj = Object.create( x );
obj.foo = 'foo';
obj.bar = 'bar';
})(o);

alert( o.foo ); // undefined

So any properties you add to obj will be not be added to o. Any properties added to obj with the same property name as a property in o will shadow the o property.

Of course, any properties added to o will be available from obj if they're not shadowed, and all objects that have o in the prototype chain will see the same updates to o.

Also, if obj has a property that references another object, like an Array, you'll need to be sure to shadow that object before adding members to the object, otherwise, those members will be added to obj, and will be shared among all objects that have obj in the prototype chain.

var o = {
baz: []
};
(function(x){
var obj = Object.create( x );

obj.baz.push( 'new value' );

})(o);

alert( o.baz[0] ); // 'new_value'

Here you can see that because you didn't shadow the Array at baz on o with a baz property on obj, the o.baz Array gets modified.

So instead, you'd need to shadow it first:

var o = {
baz: []
};
(function(x){
var obj = Object.create( x );

obj.baz = [];
obj.baz.push( 'new value' );

})(o);

alert( o.baz[0] ); // undefined


Related Topics



Leave a reply



Submit