Sub topic 11
Passing Primitives and Objects
This chapter assumes you can declare and call functions and know how JavaScript objects and arrays work. It explains what a function can and cannot change about the values its caller passes in.
The working model: call by sharing
JavaScript always passes arguments by value. When you call a function, each parameter gets a copy of the argument's value. The rules differ by type because the copied value differs:
- For a primitive (number, string, boolean,
null,undefined, bigint, symbol), the copy is the value itself. - For an object (including arrays and functions), the copy is a reference to the same object in memory.
This model is often called call by sharing. The caller and the function share the same object but hold separate variables that point to it.
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"Each of the three lines inside update does something different:
| Operation | Effect on caller |
|---|---|
| `count = count + 1` | None. Only the local copy of the number changes. |
| `user.name = "Bo"` | Visible. It changes the object that both variables point to. |
| `user = { name: "Cy" }` | None. The local `user` now points to a new object, and `u` still points to the original. |
Common errors
Assuming reassignment affects the caller. Writing list = [] inside a function does not clear the caller's array. To empty the caller's array in place, use list.length = 0.
Accidental mutation. A helper that sorts or pushes onto its argument changes the caller's data, and this is a common source of bugs that are hard to trace. Array.prototype.sort sorts the array in place:
function topScore(scores) {
return scores.sort((a, b) => b - a)[0]; // mutates scores!
}
const scores = [3, 9, 5];
console.log(topScore(scores)); // 9
console.log(scores); // [9, 5, 3], the caller's order is lostCopy the array first, or use a method that does not mutate:
function topScore(scores) {
return [...scores].sort((a, b) => b - a)[0];
// or: return scores.toSorted((a, b) => b - a)[0];
}Exercise
What does this code log, and why? function reset(arr) { arr.push(0); arr = []; arr.push(1); } const data = [5]; reset(data); console.log(data);
Show answer
It logs [5, 0]. The push(0) mutates the shared array. The line arr = [] makes the local parameter point to a new array, so push(1) affects only that new array and the caller never sees it.
Exercise
A function receives a string s and runs s = s.toUpperCase(). Does the caller's string change?
Show answer
No. Strings are primitives and cannot be changed in place. toUpperCase returns a new string, and the assignment changes only the local parameter.