Intentional in-place updates
Update a mutable object in a function when the caller should observe the change.
JS Puzzles · Const
JavaScript passes arguments by value, not by reference. For object arguments, the copied value still identifies the same object, so property mutations are visible to the caller while parameter reassignment is local.
JavaScript passes arguments by value. When that value identifies an object, both the caller and the parameter can refer to the same object, so property mutations are visible outside the function; reassigning the parameter only changes the local parameter binding.
function functionName(parameter) { /* body */ }const original = { count: 0 };
function update(object) {
object.count += 1; // mutation is visible outside
object = null; // reassignment is local
}
update(original);
console.log(original.count); // 1Mutating the shared object is observable through the original variable, but assigning a new value to the parameter does not replace the caller's variable.
Update a mutable object in a function when the caller should observe the change.
Avoid changing shared state by returning a new object rather than mutating an argument.
JavaScript arguments are passed by value. For an object, the copied value is an object reference, so changing a property affects the same object seen by the caller, while assigning a new object to the parameter does not change the caller's binding.
Follow-up: What term more accurately describes object arguments? Object arguments are commonly described as passed by sharing: the reference value is copied, and both bindings can reach the same object.
No. If a function assigns parameter = null or parameter = {}, only its local parameter changes. The caller's variable still contains its original value.
Follow-up: How can a function change the caller-visible object? It can mutate the object's existing properties, or explicitly return a replacement for the caller to assign.
object.property = value visible outside a function?A property mutation operates on the shared object, so the caller observes it. Parameter reassignment changes only which value the local parameter refers to.
Follow-up: What design choice avoids unintended mutation? Create and return a copy, then have the caller use the returned value instead of modifying the shared object.
object argumentsparameter reassignmentobject mutationpass by sharing