JavaScript by Reference Vs. by Value

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"

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 reference vs value - arrays

You aren't modifying the array.

You're changing the value of the array variable (from a reference to the old array to a reference to a new array).

For comparison, if you were to modify the existing array:

let arr = [1, 2];

console.log(arr);

add(arr, 3)

console.log(arr);

function add(array, el) {

array.length = 0;

array.push(el);

console.log(array);

}

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

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

Pass by Value and Pass by Reference in Javascript

Objects and arrays are passed by reference. Primitive values like number, string, boolean are passed by value. A reference to an object is also a primitive type and passed by value like other primitive types, but the object it refers to is still passed by reference.

This is not Angular or TypeScript specific, just how JavaScript works.

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

Primitive value vs Reference value

A variable can hold one of two value types: primitive values or reference values.

  • Primitive values are data that are stored on the stack.
  • Primitive value is stored directly in the location that the variable accesses.
  • Reference values are objects that are stored in the heap.
  • Reference value stored in the variable location is a pointer to a location in memory where the object is stored.
  • Primitive types include Undefined, Null, Boolean, Number, or String.

The Basics:

Objects are aggregations of properties. A property can reference an object or a primitive. Primitives are values, they have no properties.

Updated:

JavaScript has 6 primitive data types: String, Number, Boolean, Null, Undefined, Symbol (new in ES6). With the exception of null and undefined, all primitives values have object equivalents which wrap around the primitive values, e.g. a String object wraps around a string primitive. All primitives are immutable.



Related Topics



Leave a reply



Submit