Junior
What does it mean when an object is passed by reference?
sobes.tech AI
Answer from AI
When passing an object by reference, a pointer to the memory area where the object is stored is passed, not a copy of the object itself. Changes made to the object through the reference are reflected on the original object because they work with the same memory area. This contrasts with passing by value, where a copy of the object is passed.
Consider an example in JavaScript (where objects are passed by reference):
// Create an object
let originalObject = { name: 'Alice' };
// Function that takes an object and changes its property
function changeObjectName(obj) {
obj.name = 'Bob';
}
// Pass originalObject to the function
changeObjectName(originalObject);
// originalObject.name is now 'Bob' because the function worked with the same reference
console.log(originalObject.name); // Outputs: Bob
If the object were passed by value, changes inside the function would not affect originalObject.
In JavaScript, primitive types (strings, numbers, boolean values, null, undefined, Symbol, BigInt) are passed by value. Objects (including arrays and functions) are passed by reference.