Passing By Value and Passing By Reference
tl;dr Javascript passes its’ primitive types by value, and its’ non-primitive types by reference.
“Value” and “Reference” here are referring to a variables position in memory. In other words, when we ask programs to access data it needs to know where to look.
To understand the difference between primitive and non-primitive data types in Javascript look here(/code/javascript/javascript-data-types)
How Primitive Types Are Passed
const x = 123;
const y = x;
console.log(x); // 123 console.log(y) // 123
This is to be expected, but whats actually happening here is that when 123 is assigned to x, it’s given a space in memory. When y is given the assignment of x, y is actually given a new space in memory, copying the value of x.
const x = 123; // 0x001
const y = x; // 0x002
This can be illustrated further by changing the values of variables even more
var y = 123; // y pointing to a memory address containing the value 123
var z = y;
// Changing the value of y
y = 789;
console.log(z); // 456
Trying to do this kind of assignment with const will chuck an Uncaught TypeError: Assignment to constant variable error, let however is fine.
What this all means though, is that primitive types are passed by their value in memory. How Non Primitive Types Are Passed
Lets change the previous example to use a non-primitive type such as an object
/*
We can also use 'const' here instead of var, why?
The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable — this means that the variable identifier cannot be reassigned. For instance, in the case where the content is an object, this means the object's contents (e.g. its' properties) can be altered.
*/
const obj1 = { name: "William", surname: "Turner" };
const obj2 = obj1;
// changing a value in obj1
obj1.name = "Bootstrap";
console.log(obj2); // [object Object] /* { "name": "Bootstrap", "surname": "Turner" }*/
This time we are returned the change we made as the assignment operator directly passes a reference to the address, rather than a new copy of the value in memory. Hence, non-primitive types are passed by reference. Further Reading
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const