Are objects passed by reference?
Practice this questionWANT TO UNDERSTAND THE CONCEPT FIRST?Learn Are objects passed by reference?
Definition:
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.
Key points:
-
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.
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.
Interview point:
- 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?”. Code examples are study fragments. Difficulty and core labels are editorial estimates; version-specific behavior should be checked against your project.