Sub topic 13
Passing Primitives and Objects
This chapter assumes you can declare and call functions, use let and const, and work with arrays and objects. It explains one question that causes many real bugs: when you pass a value into a function and the function changes its parameter, does the caller see the change?
JavaScript has one rule for this, and it covers every type. Each argument is copied into its parameter. The details depend on what was copied: a primitive value itself, or a reference to an object.
The Rule: Call by Sharing
A parameter is a new local variable. When the function is called, JavaScript assigns each argument's value to the matching parameter, just as let param = argument; would.
- A primitive (number, string, boolean,
null,undefined, bigint, symbol) is copied. The parameter and the caller's variable are independent. - An object (including arrays, functions, maps, and dates) is never copied. The variable holds a reference to the object, and that reference is what gets copied. The parameter and the caller's variable now point to the same object.
This model is called call by sharing. People often describe it as "objects are passed by reference", but that description is wrong in a way that matters. In true pass-by-reference (as in C++ & parameters), assigning to the parameter would also change the caller's variable. JavaScript never does that.
function update(count, user) {
count = count + 1; // changes only the local copy
user.name = "Bo"; // mutates the caller's object
user = { name: "Cy" }; // rebinds the local name only
}
let n = 1;
const u = { name: "Al" };
update(n, u);
console.log(n); // 1
console.log(u.name); // "Bo"The three lines inside update do different things:
| Statement | What it changes | Visible to caller? |
|---|---|---|
| `count = count + 1` | The local variable `count` | No |
| `user.name = "Bo"` | The shared object | Yes |
| `user = { name: "Cy" }` | The local variable `user`, which now points elsewhere | No |
After the reassignment, user and u point to different objects. Any change made through user from then on is invisible to the caller.
Mutation Versus Reassignment
Two kinds of operation tell you whether a change leaks out:
- Mutation changes the contents of an object: setting or deleting a property,
push,splice,sort,reverse,Map.prototype.set, and so on. The caller sees it. - Reassignment uses
=on the parameter name itself. The caller never sees it.
Arrays follow the same rule, and many array methods mutate in place without making that obvious:
function topThree(scores) {
scores.sort((a, b) => b - a); // sorts the caller's array in place
return scores.slice(0, 3);
}
const results = [40, 90, 10, 75];
console.log(topThree(results)); // [90, 75, 40]
console.log(results); // [90, 75, 40, 10], the caller's order is goneFix it by working on a copy, or by using the non-mutating methods toSorted, toReversed, toSpliced, and with, which are available in ES2023 and later:
function topThree(scores) {
return scores.toSorted((a, b) => b - a).slice(0, 3);
}
const results = [40, 90, 10, 75];
console.log(topThree(results)); // [90, 75, 40]
console.log(results); // [40, 90, 10, 75]Why Strings Behave Like Values
Strings are primitives, and they are also immutable. No operation changes a string in place. Methods such as toUpperCase or replace return a new string. That means a function cannot change a caller's string by any route: it can only return a new one.
function shout(text) {
text = text.toUpperCase(); // new string, assigned locally
return text;
}
const word = "hi";
console.log(shout(word)); // "HI"
console.log(word); // "hi"Defensive Copies and Their Depth
If a function needs to change an object it received without affecting the caller, copy the object first. Choose the copy depth deliberately.
| Technique | Depth | Notes |
|---|---|---|
| `{ ...obj }`, `Object.assign({}, obj)` | Shallow | Nested objects are still shared |
| `[...arr]`, `arr.slice()` | Shallow | Nested elements are still shared |
| `structuredClone(obj)` | Deep | Handles cycles, Maps, Dates; throws on functions and DOM nodes |
| `JSON.parse(JSON.stringify(obj))` | Deep (lossy) | Drops `undefined` and functions, turns Dates into strings |
Shallow copies are a common source of half-fixed bugs:
function withDarkTheme(settings) {
const copy = { ...settings };
copy.theme.mode = "dark"; // copy.theme is the same object as settings.theme
return copy;
}
const original = { user: "Ana", theme: { mode: "light" } };
withDarkTheme(original);
console.log(original.theme.mode); // "dark", the caller was still changedCopy each level you modify, or clone deeply:
function withDarkTheme(settings) {
return { ...settings, theme: { ...settings.theme, mode: "dark" } };
}
const original = { user: "Ana", theme: { mode: "light" } };
const updated = withDarkTheme(original);
console.log(original.theme.mode); // "light"
console.log(updated.theme.mode); // "dark"Destructured Parameters Follow the Same Rule
Destructuring in a parameter list assigns each property to a local variable. Primitive properties become independent copies. Object properties are still shared references.
function rename({ name, tags }) {
name = "changed"; // local only
tags.push("new"); // the caller's array
}
const item = { name: "lamp", tags: ["home"] };
rename(item);
console.log(item.name); // "lamp"
console.log(item.tags); // ["home", "new"]Preventing Mutation
To make accidental mutation fail loudly, freeze the object. Object.freeze is shallow, like spread. In strict mode (which includes ES modules and classes), writes to a frozen object throw a TypeError. In sloppy-mode scripts they fail silently.
"use strict";
const config = Object.freeze({ retries: 3, limits: { max: 10 } });
function tweak(c) {
try {
c.retries = 5;
} catch (e) {
console.log(e instanceof TypeError); // true
}
c.limits.max = 99; // allowed: the nested object is not frozen
}
tweak(config);
console.log(config.retries, config.limits.max); // 3 99Design Guidance
- Prefer functions that return new values over functions that mutate their inputs. They are easier to test and reason about, and they work with frozen data.
- If a function must mutate an argument for performance or by design, say so in its name and documentation, for example
sortInPlaceorappendTo(list, item), and consider returning nothing so callers don't mistake it for a pure function. - Never rely on reassigning a parameter to send a result back. Return the value instead. The next chapters cover return values in detail.
- Watch for mutating methods (
sort,reverse,splice,push,fill) on arrays that came in as arguments.
Exercise
What does this code log, and why? function reset(list) { list.length = 0; list = [1, 2, 3]; } const data = [7, 8]; reset(data); console.log(data);
Show answer
It logs []. Setting list.length = 0 mutates the shared array and empties the caller's array. The later list = [1, 2, 3] only rebinds the local parameter, so data is not affected by it.
Exercise
A function addTag(post, tag) does post.tags.push(tag) and returns post. Rewrite it so the caller's post, including its tags array, is never changed.
Show answer
function addTag(post, tag) { return { ...post, tags: [...post.tags, tag] }; } The spread copies the outer object, and the new array literal replaces the shared tags array, so neither level of the original is mutated.
Exercise
Is JavaScript pass-by-reference for objects? Give a one-line test that settles it.
Show answer
No. It is call by sharing: the reference is passed by value. Test: function f(o) { o = {}; } const x = { a: 1 }; f(x); x still equals { a: 1 }. Under true pass-by-reference, x would have become {}.