Does JavaScript Pass by Reference

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

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.)

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 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.

Why does javascript pass objects by reference?

What are we passing by?

JavaScript does not pass objects by reference. It passes objects by reference values like C# and Java. JavaScript is always pass by value - that value might just happen to be a reference to an object.

function foo(obj){
obj = {};
}
var o = {x: 5};
foo(o);
console.log(o.x); // 5, proof that JavaScript is pass-by-value

For example, in C++:

void foo(int& i){
i = 5;
}
int j = 10;
foo(j);
std::cout << j; // logs 5, this is what pass-by-reference is

Primitives in JavaScript are values, passing them by reference would be meaningless since by being values they're immutable anyway (you can't change the number 5).

But values have much better!

I agree, values have much nicer semantics. You can't return value that will be modified from an unknown location by mistake. It's a lot clearer and it turns out it's very easy to optimize. Immutability in general is gaining a lot of momentum in JavaScript and a lot of people (me included) are using immutable-collections (like ImmutableJS). Note that non-primitive value types are planned but are currently under specification and won't arrive before ES7.

This is the only reference I could find about it, I haven't seen it discussed in the discussion mailing list but I hope it's on the way :)

Basically, the understanding that we can do this efficiently is much newer than JavaScript. JavaScript is a really fun language but remember it was designed in 10 days by a single guy in urgency. The good stuff like value objects is on its way but we'll have to do with what we have right now. If it makes you feel any better a lot of other languages do this too (like Scala, Java and C#).

JavaScript by reference vs. by value

My understanding is that this is actually very simple:

  • Javascript is always pass by value, but when a variable refers to an object (including arrays), the "value" is a reference to the object.
  • Changing the value of a variable never changes the underlying primitive or object, it just points the variable to a new primitive or object.
  • However, changing a property of an object referenced by a variable does change the underlying object.

So, to work through some of your examples:

function f(a,b,c) {
// Argument a is re-assigned to a new value.
// The object or primitive referenced by the original a is unchanged.
a = 3;
// Calling b.push changes its properties - it adds
// a new property b[b.length] with the value "foo".
// So the object referenced by b has been changed.
b.push("foo");
// The "first" property of argument c has been changed.
// So the object referenced by c has been changed (unless c is a primitive)
c.first = false;
}

var x = 4;
var y = ["eeny", "miny", "mo"];
var z = {first: true};
f(x,y,z);
console.log(x, y, z.first); // 4, ["eeny", "miny", "mo", "foo"], false

Example 2:

var a = ["1", "2", {foo:"bar"}];
var b = a[1]; // b is now "2";
var c = a[2]; // c now references {foo:"bar"}
a[1] = "4"; // a is now ["1", "4", {foo:"bar"}]; b still has the value
// it had at the time of assignment
a[2] = "5"; // a is now ["1", "4", "5"]; c still has the value
// it had at the time of assignment, i.e. a reference to
// the object {foo:"bar"}
console.log(b, c.foo); // "2" "bar"

How exactly is does pass by value and pass by reference work in javascript?

When you declare variables, the JavaScript engine allocates the memory for them on two memory locations: stack and heap.

Static data is the data whose size is fixed at compile time. Static data includes:

  • Primitive values (null, undefined, boolean, number, string, symbol, and BigInt)
  • Reference values that refer to objects.

Because static data has a size that does not change, the JavaScript engine allocates a fixed amount of memory space to the static data and store it on the stack.

For example, the following declares two variables and initializes their values to a literal string and a number:

let name = 'John';
let age = 25;

Because name and age are primitive values, the JavaScript engine stores these variables on the stack as shown in the following picture:
Sample Image

Unlike the stack, JavaScript stores objects (and functions) on the heap.
The JavaScript engine doesn’t allocate a fixed amount of memory for these objects. Instead, it’ll allocate more space as needed.

The following example defines the name, age, and person variables:

let name = 'John';
let age = 25;

let person = {
name: 'John',
age: 25,
};

Sample Image

In this picture, JavaScript allocates memory on the stack for the three variables name, age, and person.

The JavaScript engine creates a new object on the heap memory. Also, it links the person variable on the stack memory to the object on the heap memory.

Because of this, we say that the person variable is a reference that refers to an object.

Please check here for details



Related Topics



Leave a reply



Submit