Table of Contents
JavaScript pass by reference means passing a non-primitive data type variable (such as objects, arrays, and functions) as a reference or address to a function parameter. Any changes made to the reference variable inside the function also change the original variable, as it was passed by address and not by value.
In JavaScript, we can pass function parameter values in two ways. Passed by value, and passed by reference.
JavaScript pass by value means to pass a primitive data type variable (such as a string, number, null, undefined, or boolean) value into a function parameter. Any changes made to the reference variable inside the function do not change the original variable value.
In this “javascript pass by reference or value,” we are going to discuss everything about those, including working code examples. So stay with us.
Look at the JS Pass by Value Code Example
<script>
function updateVersion(version) {
version = version+1;
// invoked first
console.log(version); //Output: 3
}
let version = 2;
// Pass version to the updateVersion version parameter
let nextVersion = updateVersion(version);
// updateVersion function modified the version value
// But we don't see any impact in this caller section
// JavaScript Pass by Reference or Value
console.log(version); // Output: 2
</script>
In this example, we define a function called updateVersion that takes a parameter called version. Inside the function, we increase the version number by 1. Print the updated version number into the console.
We declare a variable called version and assign it the value of 2. Now we call the updateVersion function and pass the version variable as an argument. Finally, we print the value of the version variable to the console.
What do we find? We see that the value of version within the updateVersion function is 3. But after calling the function, the version variable value is changed, and it’s 2.
Because the updateVersion function did not modify the caller version variable, rather, the function created a copy of the version variable first and then increased it by 1.
As the caller variable was not changed in the programming language, we termed it “Call by Value”. A classic example of “JS Pass by Value”.
Look at the JavaScript Pass by Reference Code Example
<script>
// JavaScript Pass by reference
function updateVersion(version) {
version.V = version.V+1;
// JS pass by reference
console.log(version.V); //Output: 3
}
let version = {V:2};
// Pass version object to the updateVersion version parameter
updateVersion(version);
// updateVersion function modified the version value
// Now we see the impact in this caller section
// JS pass by reference
console.log(version.V); // Output: 3
</script>
In this example, we have created a version object and passed it to the updateVersion function, which then changes the V property of the version object. Print the updated version number into the console, and we found the updated version number 3.
But when we print the version number outside the updateVersion function, we see that our version number has also changed to 3.
It’s happened because when we send a non-primary data type as a function parameter, JavaScript automatically considers it a pass-by-reference, not a pass-by-value, and doesn’t make another copy of the caller variable. Rather, use the caller variable address within the function. That’s why we see the version number also updated in the caller variable after the execution of the updateVersion function. A classic example of “JS Pass by Reference”.
A Detail Overview of JS Pass by Value
In JavaScript, whenever we pass a primitive datatype variable as an argument to a function, a complete new copy of the caller variable is made to the memory.
That’s why if we make any changes to the newly created copy inside the function, it will not affect the caller’s copy (previous) outside the function.
It’s a JavaScript default behavior. We don’t need to mention any operator or key indication to prepare a function parameter to receive a value.
The most common examples of value types in JavaScript are primitive data types such as number, string, and boolean.
- Number: This primitive datatype or value type is used to store numerical values such as 1, 2, 3, etc.
- String: This primitive datatype or value type is used to store a list of characters, such as “JavaScript” or “HTML”.
- Boolean: This primitive datatype or value type is used to store either true or false.
A Detail Overview of JS Pass by Reference
In JavaScript, whenever we pass a non-primitive datatype variable as an argument to a function, unlike pass-by-value, the function won’t create a new copy of the variable in memory. Rather, re-use the same copy of the caller variable.
That’s why if we make any change within the function, it will definitely affect the caller’s copy (previous) outside the function as both variables use the same underlying memory address.
The most common examples of non-primitive data types or reference types in JavaScript are objects and arrays.
- Object: The object data type stores a collection of key-value pairs.
- Array: The array data type stores a collection of the same type of values.
More Example to Demonstrate JavaScript Pass by Reference
Using Array
<script>
function updateVersion(versionParam) {
versionParam.push(5);
versionParam.log(versionParam.length); //Output: 5
console.log(versionParam); //Output: [1, 2, 3, 4, 5]
}
var version = [1, 2, 3, 4];
// Pass version array to the updateVersion version parameter
updateVersion(version);
// updateVersion function modified the version array
// Check the impact of caller array - now state changed
// JavaScript Pass by Reference or Value
console.log(version.length); // Output: 5
console.log(version); // Output: [1, 2, 3, 4, 5]
</script>
Here we declared an array version with 4 elements. Pass this array to the updateVersion function’s versionParam parameter. Add an extra element in the array versionParam. Print this array length and full array in the console. The output we received is 5 and [1, 2, 3, 4, 5], respectively.
Now in the outside function, we also print the array version length and the full array in the console. But we found that the version array is now the same as the updateVersion versionParam array.
Because in JavaScript, whenever you pass a non-primitive datatype, more specifically an array or an object, to a function parameter, then it’s passing the variable reference or address. Means caller variable, and the called variable points to the same address or reference.
Using Object
Now it’s time to prove that JS uses pass by reference in case of object’s also. Let’s look at following example:
<script>
// JS call by reference
function updateVersion(versionParam) {
versionParam.vNo=versionParam.vNo+1;
console.log(versionParam); //Output: {vNo: 2}
}
var version = {vNo: 1};
// Pass version array to the updateVersion version parameter
// JavaScript call by reference example
updateVersion(version);
// updateVersion function modified the version object
// Check the impact of caller object - now state changed
console.log(version); // Output: {vNo: 2}
</script>
Difference Between JavaScript Pass by Value and JavaScript Pass by Reference
Ok, so far we have discussed all the aspects of JS pass by value and JavaScript pass by reference. Now we are going to summarize the differences now in table for your convenience:
JavaScript Pass by Value | JavaScript Pass by Reference |
---|---|
The caller variable is not changed on changes in called variables. | The caller variable is changed on changes in called variables. |
Caller variable address and the called variable address is different in memory. | Caller variable address and the called variable address is same in memory. |
JS pass by value – denotes to pass a primitive datatype to a function parameter. | JS pass by reference – denotes to pass a non-primitive datatype to a function parameter. |
A bit slower, because JS creates a copy of the caller variable. | A bit faster, because called variable uses the same address of caller variable. No overheads for copying large data structure means object or array. |
Conclusion
So far, we have tried our best to explain the full concept of JavaScript pass by value and JavaScript pass by reference using multiple examples.
We have crafted a table to mention a clear difference between JavaScript pass by value and JavaScript pass by reference.
I hope this article will help. If you found it helpful, please share the article with your developer friends on social media. Or leave a comment to support us.
FAQs on JavaScript Pass by Reference
Is JavaScript a pass-by-reference or pass-by-value language?
JS is basically a “pass by value” language. But it automatically uses “pass by reference” while dealing with objects and arrays.
Can we force pass by reference in JavaScript?
No, you cannot force it. JavaScript automatically uses pass by reference while dealing with objects or arrays.
How to pass variable by reference in JS?
There is no modifier in JavaScript for pass by reference. Whenever you pass an object or an array to a function parameter then JavaScript automatically use call by reference.
How do I prevent JavaScript from passing by reference when passing an array?
You have to do either a shallow copy or deep copy first. Then passed the copied variable. So the original variable will remain unchanged. Such as:
var courses = [‘JavaScript’,’HTML’,’CSS’];
var cpyCourses = courses.slice(-1);
Now you can pass the cpyCourses instead of courses array.
🏋️♂️ Discover Code Blocks From 20+ yrs JS Expert
💥 Asp.net C# Developer
🏆 Solution Architect
👨✈️ Database Administrator
📢 Speaker
🎓 MCTS since 2009
Leave a Reply