⏱ 0:03est. 4 min
Chapter 36- Conceptual Aside (By Value vs By Reference)
Notes
Pass by value
if a variable is primitive and it's equated to other variable then a copy of primitive value is created.
a = 3 // primitive value, It will sit in one address location in memory
b = a // copy of primitive value will be assigned to b, It will sit in other address location in memory
Pass by reference (objects)
If we set a variable equals to an object we get a location an address in memory that knows where that object lives and that's how we reference it but when other b = a or we pass a to a function that new variable b instead of getting a new location in memory simply points to the location in memory a does, No new object is created, no copy of the object is created instead 2 names points to the same memory location This is called by reference
Example 1
//by value (primitives)
var a = 3;
var b;
b=a;
a = 2;
console.log(a); //2
console.log(b); //3
new a will be 3 and b will be 3 sitting on different memory spots. That means we can change a and it will not affect b they are on their on.
//by reference (all objects (including functions))
var c = { greeting:'hi'};
var d;
d=c;
Now they are not copies of each other
c.greeting = ‘hello';//mutate
#BIGWORD mutate - To change something "immutable can't be changed "
console.log(c); // {greeting : "hello"}
console.log(d); // {greeting : "hello"}
//by reference (even as parameters)
function changeGreeting(obj){
obj.greeting = ‘hola'; //mutate
}
changeGreeting(d);
console.log(c); // {greeting : ‘hola'}
console.log(d); // {greeting : ‘hola'}
//equals operator sets up new memory space (new address)
c = {greeting : ‘howdy'}
console.log(c); // {greeting : ‘howdy'}
console.log(d); // {greeting : ‘hola'}