Check out my Github for my free-to-read JavaScript Ebook that covers all the new features from ES6 to 2021. If you want find a great place for interactive tutorials, i recommend Educative where you can find my JavaScript course
This website contains affiliate links.
If you just started learning how to code you may have heard the terms pass by value and pass by reference but you may not be 100% clear as to what they mean.
In this article we will go over the difference between the two, using JavaScript
as the language of reference.
First of all, let’s define what these two terms mean:
JavaScript
always passes arguments by values, meaning that a new variable is created inside the scope of the function so changing its value inside of it will not affect what’s outside of the scope.
Let’s look at this simple example:
function incrementNumber(num) { num = num + 1 console.log(num) } let myNumber = 1 incrementNumber(myNumber) // 2 console.log(myNumber) // 1
As you can see, the value got updated inside of the function, but the original variable that we passed as the argument of the function did not change.
We just mentioned that JavaScript
always passes arguments by value so when is it that we actually can leverage passing by reference?
Let’s look at this example:
function increaseAge(person) { person.age = person.age + 1 console.log(person.age) } const me = { name: 'Alberto', age: 27, } increaseAge(me) // 28 console.log(me.age) // 28
As you can see, this time instead of a Primitive, I passed an Object and when I changed the value of a property of that object, the change was reflected outside of the scope of the function.
Does this mean that Objects are passed by reference in JavaScript
? The answer is no and this simple example will show you why JavaScript
always passes by value.
function increaseAge(person) { person = { name: 'Alberto', age: person.age + 1, } console.log(person.age) } const me = { name: 'Alberto', age: 27, } increaseAge(me) // 28 console.log(me.age) // 27
What happened here? Why this time when we accessed me.age
the value was not changed?
The reason is that the Object is passed by value but its value (its properties) is just a reference to that of the original Object. That’s why when we changed a property of the object inside of our function, that change was reflected outside of it but when we change the Object itself to a new one the change was not reflected outside because we changed the new one that lived inside of the function scope.