Are objects passed by reference?
Try code in the playgroundUnderstand the concept
JavaScript passes every argument by value. For an object, the copied value is a reference to that object, so the caller and function can still reach the same underlying object. This explains why changing a property affects the caller, but assigning a new object to the parameter does not.
Important ideas
-
JavaScript passes values; for an object, that value is a reference.
-
Changing a shared object's property affects the original object.
-
Reassigning a function parameter does not reassign the caller's variable.
-
Primitive values such as numbers and strings do not share mutable object contents.
-
Arrays and functions are objects too, so the same reference behavior applies to them.
Work through the example
function update(user) {
user.name = 'Neha';
user = { name: 'Ravi' };
}
const original = { name: 'Asha' };
update(original);
console.log(original.name); // Neha- The property change affects the shared object; reassigning the parameter only changes that local binding.
Can you explain it without the notes?
Are objects passed by reference?
Use your own words. Explain an example and one limitation before checking the explanation.
Check your explanation
JavaScript passes every argument by value. For an object, the copied value is a reference to that object, so the caller and function can still reach the same underlying object. This explains why changing a property affects the caller, but assigning a new object to the parameter does not.
Turn this concept into a clear answer.
- Say “a copy of the object reference is passed” rather than “the caller's variable is passed by reference.”
Adapted from 01_JAVASCRIPT_TYPESCRIPT.md · “Are objects passed by reference?”. Examples are study fragments; framework behavior can depend on your version.