Javascript Pass By Reference Or Value

5 min read

JavaScript pass by reference or value is a fundamental concept that dictates how data is stored, copied, and manipulated in memory. Understanding this mechanism is not merely an academic exercise; it is the key to preventing frustrating bugs where variables change unexpectedly, functions mutate original data, or equality checks fail silently. At its core, JavaScript uses a single evaluation strategy called Call by Sharing, though it is often colloquially—and sometimes confusingly—described as "pass by value for primitives, pass by reference for objects Took long enough..

The Core Distinction: Primitives vs. Objects

To grasp how JavaScript handles assignment and function arguments, you must first distinguish between the two categories of data types.

Primitive Types represent simple, immutable values. There are seven of them: string, number, bigint, boolean, undefined, symbol, and null. When you assign a primitive to a variable, the variable holds the actual value itself Not complicated — just consistent..

Object Types (often called Reference Types) represent complex data structures. This category includes Object, Array, Function, Date, RegExp, Map, Set, and others. Variables assigned an object do not hold the object itself; they hold a reference (a memory address pointer) to the location where the object lives in the heap.

How Assignment Works: Copying the Container

The behavior of the assignment operator (=) reveals the "pass by value" nature of the language. In JavaScript, everything is passed by value. The critical nuance is what that value represents Not complicated — just consistent..

Primitives: True Value Copy

When you assign a primitive variable to another variable, JavaScript creates a completely independent copy of the value It's one of those things that adds up. Which is the point..

let score = 100;
let highScore = score; // Copies the value 100

highScore = 150; 

console.log(score);     // 100 (Unaffected)
console.log(highScore); // 150

Here, highScore gets its own distinct slot in memory containing 100. But changing highScore simply overwrites that slot. The original score remains untouched because they are two separate values.

Objects: Reference Copy (Call by Sharing)

When you assign an object variable to another variable, JavaScript copies the reference (the address), not the object itself. Both variables now point to the exact same object in memory.

let user = { name: 'Alex', role: 'Admin' };
let adminUser = user; // Copies the reference (address)

adminUser.role = 'Super Admin';

console.log(user.Day to day, role);      // 'Super Admin' (Original changed! )
console.log(adminUser.Consider this: role); // 'Super Admin'

Because user and adminUser share the same reference, mutating the object via one variable is visible through the other. This is not "pass by reference" in the traditional C++ sense (where you could swap the pointer itself). And you cannot reassign the original variable's binding from inside a function. You can only mutate the contents of the shared object.

Function Arguments: The Practical Implication

Function invocation is essentially implicit assignment. Parameters behave exactly like the assignment examples above.

Passing Primitives: Isolation Guaranteed

When a primitive is passed to a function, the parameter becomes a local variable holding a copy of the value. The original variable outside the function is completely shielded.

function increment(value) {
    value = value + 1; // Modifies the local copy only
    console.log('Inside:', value);
}

let count = 5;
increment(count); // Inside: 6
console.log('Outside:', count); // Outside: 5

Passing Objects: Shared Mutation

When an object is passed, the parameter receives a copy of the reference. The function cannot replace the original object in the caller's scope, but it can mutate its properties.

function updateProfile(profile) {
    // MUTATION: Affects the original object
    profile.lastLogin = new Date();
    
    // REASSIGNMENT: Does NOT affect the original variable
    profile = { name: 'New User', lastLogin: new Date() };
    console.log('Inside (reassigned):', profile);
}

const currentUser = { name: 'Jordan', lastLogin: null };
updateProfile(currentUser);

console.log('Outside:', currentUser); 
// Output: { name: 'Jordan', lastLogin: [Date Object] }
// The 'name' remained 'Jordan' because reassignment only changed the local parameter pointer.

This distinction—Mutation vs. Reassignment—is the single most important takeaway for JavaScript developers. Even so, * Mutation (changing properties: obj. prop = x, arr.push(y)) affects the shared object Took long enough..

  • Reassignment (changing the variable binding: obj = {}) only redirects the local variable to a new memory address, leaving the original reference intact.

Common Pitfalls and "Gotchas"

1. The const Misconception

Developers often believe const makes objects immutable. It does not. const prevents reassignment of the variable identifier, not mutation of the value it points to Still holds up..

const config = { apiUrl: 'https://api.example.com' };
config.apiUrl = 'https://new-api.example.com'; // Valid! Mutation allowed.
config = {}; // TypeError: Assignment to constant variable. Reassignment blocked.

2. Array Methods: Mutators vs. Non-Mutators

This is a frequent source of bugs in React, Vue, or state management libraries (like Redux) where immutability is required.

  • Mutators (Change original reference): push, pop, shift, unshift, splice, sort, reverse, fill.
  • Non-Mutators (Return new array): map, filter, reduce, concat, slice, flat, filter, find.
const numbers = [3, 1, 2];

// DANGER: sorts in place, returns reference to same array
numbers.sort(); 
// numbers is now [1, 2, 3]

// SAFE: returns new array
const sorted = [...numbers].sort(); 
// numbers remains [1, 2, 3], sorted is [1, 2, 3]

3. Equality Checks (===)

Because objects are compared by reference, two distinct objects with identical content are not equal.

const a = { id: 1 };
const b = { id: 1 };
const c = a;

console.log(a === b); // false (Different addresses in memory)
console.log(a === c); // true  (Same address)

Primitives, conversely, are compared by value: 10 === 10 is always true.

Strategies for Safe Data Handling

Since shared mutation is often undesirable (leading to side effects and unpredictable state), modern JavaScript development emphasizes Immutability Patterns The details matter here..

1. Shallow Cloning (Spread Syntax & Object.assign)

Creates a new object with copies of the top-level properties. Nested objects are still shared references.

const original = { user: { name: 'Sam' }, theme: 'dark' };

// Shallow copy
const copy = { ...original }; 
// OR
const copy2 = Object.assign({}, original);

copy.So theme = 'light'; // Safe: primitive property changed on copy only
copy. Worth adding: user. name = 'Alex'; // DANGER: Mutates shared nested object!
console.log(original.user.

#### 2. Deep Cloning
For true isolation, you need a deep clone. Modern options include
New Additions

Brand New Reads

Based on This

You May Enjoy These

Thank you for reading about Javascript Pass By Reference Or Value. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home