Skip to the content

Lesson 48 of 296

Copy by value vs copy by reference

What you will learn

  • How primitives are copied
  • How objects and arrays are stored and shared
  • What a reference is
  • What happens when you pass values to functions
  • Mutation and why it causes bugs
  • Why const objects can still change
On this page

Primitives are copied by value

When you assign a primitive to another variable, the value itself is copied. The two variables are completely separate.

let a = 5;
let b = a;
b = 10;
console.log(a);      5
console.log(b);      10

Objects are shared by reference

An object (including arrays and functions) is stored somewhere in memory. A variable does not hold the object itself. It holds a reference: the location of the object in memory.

When you assign it to another variable, only the reference is copied. Both variables point to the same object.

const user1 = { name: "Sam" };
const user2 = user1;
user2.name = "Ali";
console.log(user1.name);     "Ali"

There is only one object. user1 and user2 are two names for it.

Memory:
user1 ----\
           >---- { name: "Ali" }
user2 ----/

Arrays work the same way:

const a = [1, 2];
const b = a;
b.push(3);
console.log(a);      [1, 2, 3]

Comparing objects

=== compares references, not contents:

{ x: 1 } === { x: 1 }      false  (two different objects)
const c = a;
c === a                    true   (same reference)

Passing values to functions

JavaScript always passes a copy of what the variable holds:

  • For a primitive: a copy of the value.
  • For an object: a copy of the reference.

So a function can change the contents of an object you pass in:

function rename(user) {
  user.name = "Changed";
}
const person = { name: "Sam" };
rename(person);
console.log(person.name);     "Changed"

But reassigning the parameter does not affect the caller:

function replace(user) {
  user = { name: "New" };
}
replace(person);
console.log(person.name);     still "Changed"

Inside the function, user now points to a new object. person outside still points to the old one.

This behaviour is sometimes called "pass by sharing". If an interviewer asks "is JavaScript pass by value or pass by reference?", the precise answer is: always pass by value, but for objects the value is a reference.

Mutation

Mutating means changing an object or array in place. Methods like push, pop, splice, sort, reverse, and assigning obj.x = ... all mutate.

Mutation of shared objects causes bugs that are hard to find: one part of the code changes data that another part was still using.

function addDiscount(basket) {
  basket.total = basket.total * 0.9;      mutates the caller's object
  return basket;
}

Better: return a new object and leave the original alone.

function addDiscount(basket) {
  return { ...basket, total: basket.total * 0.9 };
}

This immutable style is required in React state (Part 12) and Redux.

Non-mutating alternatives

Mutates the originalReturns a new copy instead
arr.push(x)[...arr, x]
arr.sort()arr.toSorted()
arr.reverse()arr.toReversed()
arr.splice(i, 1)arr.toSpliced(i, 1) or arr.filter(...)
arr[i] = xarr.with(i, x)
obj.x = 1{ ...obj, x: 1 }

toSorted, toReversed, toSpliced and with were added in ES2023 and work in all modern browsers and Node.js 20+.

const does not freeze objects

const stops the variable being pointed at a different object. It does not stop changes inside the object.

const settings = { theme: "light" };
settings.theme = "dark";       allowed
settings = {};                 TypeError

To stop changes inside, use Object.freeze:

const config = Object.freeze({ apiUrl: "/api" });
config.apiUrl = "x";           ignored (an error in strict mode)

Object.freeze is shallow: nested objects inside can still change.

Common mistakes

  • Thinking const b = a copies an object or array.
  • A function changing an object the caller still needs.
  • Using sort() or reverse() on data that other code shares.
  • Thinking const makes an object unchangeable.

How to say it in an interview

"Primitives are copied by value. Objects, arrays and functions are held by reference, so assigning one to another variable shares the same object, and triple equals compares references, not contents. JavaScript always passes arguments by value, but for objects that value is a reference, so a function can mutate the caller's object but cannot replace it. I avoid mutating shared data and return new objects instead, which is essential in React. const prevents reassignment, not mutation; Object.freeze prevents shallow mutation."

Key words

WordMeaning
By valueThe value itself is copied
ReferenceThe location of an object in memory
MutateChange something in place
ImmutableNot changed after creation; changes create new copies
Pass by sharingPassing a copy of a reference
Object.freezeStops changes to an object's own properties

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.