Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 156 ยท Functions

Pass by Value and Pass by Sharing

Learn how JavaScript passes arguments - copies of values, shared references to objects, mutation vs reassignment, nested data and how to protect the caller's data.

"Is JavaScript pass by value or pass by reference?" is one of the most common questions in interviews and one of the most common sources of real bugs. The short answer is that JavaScript is always pass by value, but for objects the value that gets copied is a reference. That second half is what surprises people.

The Parameters lesson showed the basic behavior. This lesson explains the model behind it, so you can predict what happens with nested data, arrays, strings, closures and nested functions, and so you know when to copy data defensively.

Two kinds of values

JavaScript values fall into two groups:

  • Primitives: numbers, strings, booleans, null, undefined, symbols and BigInts. They are immutable: you can never change a primitive, only replace it with another one.
  • Objects: everything else, including arrays, functions, dates, maps and sets. They are mutable and live in memory somewhere; a variable holds a reference (think of it as an address) pointing at the object.

When you call a function, each argument expression is evaluated and its value is copied into the matching parameter. For a primitive the copy is the primitive itself. For an object the copy is the reference, so the parameter and the caller's variable point at the same object.

JS Copies of primitives, copies of references

Press Run (or Ctrl + Enter) to see the console output here.

No output.

This model is sometimes called pass by sharing (or "call by sharing"): the function shares the caller's object, but cannot change which object the caller's variable points to.

Mutation versus reassignment

Two different operations look alike and behave very differently:

  • Mutation changes the contents of the object the parameter refers to: user.name = "Grace", list.push(1), list.sort(). The caller sees it, because it is the same object.
  • Reassignment gives the parameter a new value: user = { name: "Grace" }. This only rebinds the local name. The caller's variable is untouched.

The classic proof that JavaScript is not "pass by reference" is a swap function. In a true pass-by-reference language, swap(a, b) could exchange the caller's variables. In JavaScript it cannot:

JS Why swap(a, b) can't work

Press Run (or Ctrl + Enter) to see the console output here.

No output.

If a function needs to hand back several values, return them (an array or an object) and let the caller assign them. See Return Values.

Built-in methods mutate too

Many array methods change the array they are called on: push, pop, shift, unshift, splice, sort, reverse, fill. Passing an array to a function and calling sort() inside it silently reorders the caller's array.

JS A helper that sorts the caller's array

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The non-mutating twins toSorted(), toReversed(), toSpliced() and with() exist exactly for this reason. See Sorting Arrays.

Strings only look like objects

Strings have methods and a length, but they are primitives, and primitives are immutable. Methods such as toUpperCase() return a new string; they never change the original. Assigning to an index silently does nothing (or throws in strict mode).

JavaScript
function shout(text) {
  text.toUpperCase();      // result thrown away
  text[0] = "X";           // ignored (TypeError in strict mode)
  return text;
}
shout("hello");            // "hello"

Nested data: copies are shallow

Spreading an object or array creates a shallow copy: a new outer object whose properties hold the same inner references. Changing something nested through the copy still changes the original.

JS Shallow copy, shared inner object

Press Run (or Ctrl + Enter) to see the console output here.

No output.

For a few levels, rebuild only the branches you change. For a large structure, use structuredClone(). Copying Objects compares all the options, including what structuredClone cannot copy (functions, for example).

Nested functions and closures

An inner function does not receive copies of the outer function's variables. It keeps access to the variables themselves through a closure, so it sees changes to them, whether the variable holds a primitive or an object.

JS Inner functions share the outer variable

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Contrast this with passing a primitive as an argument to an inner function: function bump(n) { n++ } gets its own copy. The difference is whether the inner function receives the value as a parameter or reads an outer variable.

Protecting data from surprise changes

When you do not want a function to change what you gave it, you have several options, from lightweight to strict:

  1. Do not mutate parameters. Build and return new values with spread, map, filter, toSorted and friends.
  2. Copy at the boundary. If a function must mutate, mutate a copy it made (const local = [...input]).
  3. Freeze. Object.freeze(obj) makes the top level read-only. It is shallow, and in sloppy mode failed writes are silent, so combine it with strict mode or tests.
  4. Document intent. A name like sortInPlace tells callers that the function mutates.
JS Freezing is shallow

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which statement about JavaScript's argument passing is accurate?

    Each argument is copied into the parameter. For objects, the copied value is a reference to the same object, which is why this is called pass by sharing.
  2. 2. What does the caller see after function f(o) { o = { x: 2 }; } is called with const a = { x: 1 }; f(a);?

    Reassigning the parameter only rebinds the local name. The caller's variable still points at the original object.
  3. 3. Why does a helper that calls scores.sort() on its parameter surprise callers?

    Array sort() reorders the original array. Copy first with [...scores], or use toSorted().
  4. 4. After const copy = { ...order }, what happens when you change copy.customer.city?

    Spread copies only the top level. Nested objects are shared. Use structuredClone() or copy the nested path you change.
  5. 5. What does Object.freeze(config) protect?

    Freezing is shallow: nested objects stay mutable unless you freeze them as well.

Summary

  • JavaScript always passes arguments by value; for objects, the copied value is a reference, so the function shares the object.
  • Mutating an object through a parameter affects the caller; reassigning the parameter does not.
  • A swap(a, b) function cannot swap the caller's variables; return the new values instead.
  • Methods like sort, push and splice mutate in place; prefer copies or toSorted, toSpliced and similar.
  • Strings and other primitives are immutable; their methods return new values.
  • Spread copies are shallow; use structuredClone() or copy the nested branch you change.
  • Inner functions see outer variables (closures), but get copies when you pass values as arguments.

Next: Return Values โ€” getting results back out of your functions.