The concept of passing by reference vs passing by value is important when working with functions. Because depending on what arguments you pass into a function, its values can be changed or not changed without you knowing!
When we pass these values into functions, a copy of that value is used within our function. We don’t see the copy in our code, but it is stored in memory for our function to use.
Lets create a function that attempts modify a number:
function modifyMyNumber(numberToModify) {
console.log(numberToModify); // prints 42
numberToModify = 98;
console.log(numberToModify); // prints 98
}
var myNumber = 42;
modifyByNumber(myNumber); // runs our function
console.log(myNumber) // prints 42
You will notice that our myNumber does not change its value after its passed into our function. Thats becomes the modifyMyNumber param is given a copy of our variable that contains the same value.
You may have heard about pass by reference if you have worked with other programming languages such as Java.
In our code, variables of these data types are passed in the same way we’d pass in variables that are primitive data types, but the difference is that these types can be modified inside our function.
In Javascript, all variable types are passed into functions by value.