These are my notes taken while studying Web Dev Simplified's video tutorial on passing by reference versus passing by value in JavaScript.
When you set a variable to a primitive value or primitive data type, you are using pass by value, which means that the value is set to what the variable actually equals.
let a = 10; // 10
let c = a; // 10
c = c + 1; // 11
In this example, "c" is set to the value of 10 and "a" is set to the value of 10, but they are two different values. So when one is added to "c," it updates "c" to 11, but "a" remains 10.
When you set a variable to an array or object, you are using pass by reference, which means that the value is set to a reference to that array or object.
let d = [1, 2]; // Memory address that has the value of [1, 2]
let e = d; // The same memory address as d that has the value of [1, 2]
Both "d" and "e" will point to the same memory address in your code. This means that if you update the value of "d," the value of "e" will aslo be updated.
If, however, you set "e" to a new array, it will create a new address in memory that has the value of that new array.
e = [3, 4] // New memory address that has the value of [3, 4]
- Reference Vs Value In JavaScript by Web Dev Simplified