This is more explanation for Pass by value and Pass by reference (Javascript).
In this concept, they are talking about passing the variable by reference and passing the variable by reference.
Pass by value (Primitive Type)
var a = 3;
var b = a;
console.log(a); // a = 3
console.log(b); // b = 3
a=4;
console.log(a); // a = 4
console.log(b); // b = 3
- applies to all primitive type in JS(string, number, boolean, undefined, null).
a
is allocated a memory (say 0x001) and b
creates a copy of the value in memory (say 0x002).
- So changing the value of a variable doesn't affect the other, as they both resides in two different locations.
Pass by reference (objects)
var c = { "name" : "john" };
var d = c;
console.log(c); // { "name" : "john" }
console.log(d); // { "name" : "john" }
c.name = "doe";
console.log(c); // { "name" : "doe" }
console.log(d); // { "name" : "doe" }
- JS engine assigns the object to the variable
c
, it points to some memory say (0x012)
- when
d=c
, in this step d points to the same location (0x012).
- changing the value of any changes value for both the variable.
- functions are objects
Special case, Pass by reference (objects)
c = {"name" : "jane"};
console.log(c); // { "name" : "jane" }
console.log(d); // { "name" : "doe" }
- The equal(
=
) operator sets up new memory space or address