Topic 18 of 37
Pass by vs Reference
Overview
This is one of the most critical concepts in JS. Primitives (strings, numbers, booleans) are passed by VALUE—a complete copy is made. Objects and Arrays are passed by REFERENCE—a pointer to the memory location is passed. Modifying a referenced object changes it everywhere.
Syntax
Changing 'b' does not affect 'a'.
Primitives
javascript
let a = 10;
let b = a; // A copy is made
b = 20;
console.log(a); // 10
console.log(b); // 20Because both variables point to the same array in the Heap, modifying one modifies the other.
Objects/Arrays
javascript
const arr1 = [1, 2, 3];
const arr2 = arr1; // Pointing to the SAME memory location
arr2.push(4);
console.log(arr1); // [1, 2, 3, 4] (Modified!)
console.log(arr1 === arr2); // trueCommon Pitfalls
- Thinking that `const` protects an object from being mutated. It only prevents reassignment of the variable, not mutation of the object properties.
Interview Tips
- Interviewers will ask you how to prevent accidental mutation of objects. The answer is to create copies (Shallow or Deep).
Real-World Example
In Redux or React State, mutating state directly (by reference) prevents the UI from re-rendering because React uses shallow equality checks.
example
javascript
// BAD: Mutating state directly
const user = state.user;
user.name = "Bob";
// React won't re-render because the reference hasn't changed.
// GOOD: Creating a new reference
const updatedUser = { ...state.user, name: "Bob" };