JavaScript: Pass by Value vs Pass by Reference
JavaScript handles primitive and non-primitive data types differently when passing them to functions. It uses pass by value for primitives and pass by reference for objects.
Pass by Value (Primitive Data Types)
When you pass a primitive value (e.g., numbers, strings, booleans, null
, undefined
, Symbol
, or BigInt
) to a function, JavaScript creates a copy of the value. Any modifications inside the function do not affect the original variable
.
Example: Pass by Value
let number = 10;
function modify(number) {
number = number * 2;
console.log(`The value of inside number is : ${number}`);
}
modify(number);
console.log(`The value of number is : ${number}`);
The value of inside num is : 20
The value of number is : 10
In this code, we are pass number as parameter in function modify.
number
variable holds the value 10;Next we call function modify, passing it the argument number which contains value 10.
Any change inside the modify(), does not change the value for outside number variable because we are passing copy of number .
2. Pass by Reference (Objects & Arrays)
When you pass an object (including arrays and functions) to a function, JavaScript passes a reference to the memory location of that object. Any modifications affect the original object.
Example: Pass by Reference
function modify(obj) {
obj.value = 50; // Modifies the original object
}
let myObj = { value: 10 };
modify(myObj);
console.log(myObj.value);
Output
50
In this code, first create myObj variable that contain the reference of the object.
Next , we then call modify(), pass myObj as argument.
modify() modify the value that myObj variable point to and update the vaue.
Pass by Reference with Arrays
Since arrays are objects, they also behave in a pass-by-reference manner.
function modifyArray(arr) {
arr.push(4); // Modifies the original array
}
let numbers = [1, 2, 3];
modifyArray(numbers);
console.log(numbers);
Output
[ 1, 2, 3, 4 ]