How does data transfer work by reference and by value?
sobes.tech AI
Answer from AI
Data transfer by value (by value) and by reference (by reference) determines how the original variable changes when it is passed to a function or assigned.
Transfer by value:
A copy of the variable's value is created. Any changes to this copy inside the function or during assignment do not affect the original variable. Suitable for primitive data types (numbers, strings, booleans, null, undefined, Symbol, BigInt).
// Transfer by value
let a = 10;
function modifyValue(num) {
num = 20; // Modifies the copy
}
modifyValue(a);
console.log(a); // Outputs 10 - the original value remains unchanged
Transfer by reference:
The reference (memory address) to the value is passed, not the value itself. Changes made through this reference affect the original variable. In JavaScript, this is used for objects (including arrays and functions). It is important to understand that what is passed is not the object itself, but a reference to it. When reassigning the parameter inside the function, the reference is assigned a new value, but the original variable does not change.
// Transfer by reference (for objects)
let obj1 = { value: 10 };
function modifyObject(obj) {
obj.value = 20; // Changes the object's property via the reference
}
modifyObject(obj1);
console.log(obj1.value); // Outputs 20 - the original object has changed
// Example of reassigning the parameter when passing an object
let obj2 = { value: 10 };
function reassignObject(obj) {
obj = { value: 30 }; // obj now points to a new object in the local scope of the function
}
reassignObject(obj2);
console.log(obj2.value); // Outputs 10 - the original object remains unchanged
| Characteristic | Transfer by value | Transfer by reference |
|---|---|---|
| What is transferred | A copy of the value | A reference to the value |
| Impact on the original | No | Yes (when changing properties) |
| Data types in JS | Primitive types | Objects |