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:
numberstringbooleannullundefinedsymbolbigint
Example:
javascript
let a = 5;
let b = a; // the value 5 is copied
b = 10;
console.log(a); // 5 ← unchanged
console.log(b); // 10
aandbare now two independent values. Changingbdoes not affecta.
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:
objectarrayfunctionDate,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
user2also changesuser1.
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
| Type | Where it is stored | On copying |
|---|---|---|
| Primitive (by value) | in the stack | a new copy is created |
| Object (by reference) | in the heap | the reference to the same spot is copied |
Summary
| Data type | Passing | Example |
|---|---|---|
string, number, boolean, null, undefined, symbol, bigint | by value | let a = 5; let b = a; |
object, array, function, Date, Map, Set | by reference | let 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 readyPremium
A concise answer to help you respond confidently on this topic during an interview.