
JavaScript Doesn't Pass Objects by Reference: Pass by Sharing Explained
- كاتب موثّق
- ES2025
محتويات المقال
clearFilters(filters), which sets the parameter to a fresh copy of the defaults. Nothing happens: no error, and the old filters stay applied. A few files away, a helper that "only reads" the search query adds a default sort to it, and the URL suddenly gains a sort order the user never picked. Both bugs come from the same sentence the team believes: "objects are passed by reference".
The common misconception
What actually happens
A variable holding an object holds a reference
let filters = { category: "phones" }, the object lives somewhere in memory and filters holds a reference to it. const saved = filters copies the reference, not the object, so you get two variables and one object. Nothing about this is specific to functions yet. Primitives follow the same copy rule; you just can't tell, because a number or a string can't be changed in place, so a copy and a shared value behave the same.
A call copies each argument into a new variable
Mutation goes through, reassignment doesn't
current.category = "all" follows the reference and changes the shared object, so the caller sees it. current = { ...DEFAULTS } points the local variable at a new object, and the caller's variable still points at the old one. In a language with real pass by reference, like a C# ref parameter or a C++ reference parameter, the parameter is an alias for the caller's variable, so that reassignment would reach the caller. JavaScript has no equivalent.
const DEFAULTS = { category: "all", sort: "newest" };let filters = { category: "phones", sort: "price" };function clearFilters(current) { current = { ...DEFAULTS }; // rebinds the parameter, nothing else}clearFilters(filters);console.log(filters.category); // phones: the caller's variable is untouchedconst DEFAULTS = { category: "all", sort: "newest" };let filters = { category: "phones", sort: "price" };function clearedFilters() { return { ...DEFAULTS }; // build the new value and hand it back}filters = clearedFilters(); // only the variable's owner can reassign itconsole.log(filters.category); // allfilters can point it at another object. If a function really must update the caller's object in place, it has to mutate it, for example with Object.assign(current, DEFAULTS), and its name should say so.
The other half: accidental mutation
withDefaultSort below looks like it returns an improved query, but it changes the caller's object on the way:
function withDefaultSort(query) { query.sort ??= "newest"; // mutates the object the caller passed return query;}const query = { q: "headphones", price: { max: 500 } };const sorted = withDefaultSort(query);console.log(query.sort); // newest: the caller's object changedconsole.log(sorted === query); // true: one object, two namesconst copy = { ...query };copy.q = "speakers"; // top level was copiedcopy.price.max = 900; // nested object is still sharedconsole.log(query.q, query.price.max); // headphones 900const didn't protect query. MDN describes const as an immutable binding, not an immutable value: the variable can't be reassigned, but the object's properties can still change. And spread makes a : top-level properties are copied, while nested objects like price are still shared, which is why copy.price.max = 900 changed the original too.
param.prop = value or param.push(item) | |
Object.assign(param, changes) | |
param = newObject | |
param = { ...param, prop: value } | |
count += 1 on a number parameter |
How to apply it in your project
Never reassign a parameter to "return" a value If a function computes a new object, return it and let the caller assign it. Reassigning a parameter only ever changes the function's own variable. Don't mutate what you were given Build a new object instead, like return { ...query, sort: query.sort ?? "newest" }. If in-place mutation is the point, name the function after it.Copy as deep as you change Spread one level for flat objects, spread each nested level you modify, and use structuredClonefor whole trees of plain data.Use const and freeze for what they really do conststops reassignment of a variable.Object.freezestops changes to an object, but only one level deep, so it's best as a development guard on shared configuration.
Key takeaways
JavaScript passes every argument by value; for objects, the value that gets copied is a reference. The function and the caller share the object, so mutating its properties is visible outside. Reassigning a parameter only changes the function's local variable; the caller's variable never moves. constand spread don't make objects immutable:constblocks reassignment, and spread copies one level.To replace what a caller's variable points to, return a new value and let the caller assign it.
التعليقات (0)