Skip to main content

By reference or by value

1. What "by value" means

When the variable stores the value itself, not a reference to it. Copying creates a new independent copy of the data.

Primitives (simple data types) are passed by value.

These are:

  • number
  • string
  • boolean
  • null
  • undefined
  • symbol
  • bigint

Example:

javascript
let a = 5; let b = a; // the value 5 is copied b = 10; console.log(a); // 5 ← unchanged console.log(b); // 10

a and b are now two independent values. Changing b does not affect a.


2. What "by reference" means

When the variable does not store the object itself, but stores a reference (pointer) to the place in memory where that object lives.

All objects and complex data structures are passed by reference:

  • object
  • array
  • function
  • Date, Map, Set, and so on

Example with an object:

javascript
const user1 = { name: 'Oleh' }; const user2 = user1; // the REFERENCE is copied, not the object itself user2.name = 'Maria'; console.log(user1.name); // "Maria" console.log(user2.name); // "Maria"

Both point to the same object in memory. So changing user2 also changes user1.


Visually

javascript
┌──────────────┐ │ user1 │ ─┐ └──────────────┘ │ { name: "Oleh" } ┌──────────────┐ │ │ user2 │ ─┘ └──────────────┘

3. Example with an array

javascript
const arr1 = [1, 2, 3]; const arr2 = arr1; arr2.push(4); console.log(arr1); // [1, 2, 3, 4] console.log(arr2); // [1, 2, 3, 4]

Both arrays are the same object in memory.


4. How to make a copy of an object (to avoid a reference)

If you want to create a new independent object, you need to explicitly copy the data.

Shallow copy:

javascript
const user1 = { name: 'Oleh', age: 25 }; const user2 = { ...user1 }; // spread operator user2.name = 'Maria'; console.log(user1.name); // "Oleh" console.log(user2.name); // "Maria"

Deep copy (for nested objects)

javascript
const user1 = { name: 'Oleh', address: { city: 'Kyiv' } }; const user2 = JSON.parse(JSON.stringify(user1)); // deep cloning user2.address.city = 'Lviv'; console.log(user1.address.city); // "Kyiv" console.log(user2.address.city); // "Lviv"

5. An analogy

TypeWhere it is storedOn copying
Primitive (by value)in the stacka new copy is created
Object (by reference)in the heapthe reference to the same spot is copied

Summary

Data typePassingExample
string, number, boolean, null, undefined, symbol, bigintby valuelet a = 5; let b = a;
object, array, function, Date, Map, Setby referencelet obj2 = obj1;

In short

  • By value → a copy of the data is created.
  • By reference → a pointer to the same object is copied.
  • So changing one object affects the other, if they share a reference.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.