Skip to main content

Command Palette

Search for a command to run...

JavaScript: Pass by Value vs Pass by Reference

Clearing the Confusion Around JavaScript Function Arguments

Updated
2 min read

Introduction

When working with functions in JavaScript, you’ll often hear developers debating whether JavaScript is “pass by value” or “pass by reference.” The truth is slightly nuanced. Let’s break it down with examples so you’ll never get confused again.


Pass by Value

When you pass a primitive type (like number, string, boolean, null, undefined, symbol, bigint) into a function, JavaScript passes it by value. This means the function gets a copy, and changes inside the function don’t affect the original variable.

Example:

function updateValue(x) {
  x = x + 10;
  console.log("Inside function:", x);
}

let num = 5;
updateValue(num);

console.log("Outside function:", num); // Still 5

Here, the variable num is unaffected because only a copy was modified.


Pass by Reference (Actually Reference Copy)

For objects and arrays, JavaScript passes a reference — but not the actual object itself. Instead, it passes a copy of the reference. That’s why changes to the object inside a function reflect outside.

Example:

function updateSkills(obj) {
  obj.skills.push("Node.js");
}

let user = { name: "Pratik", skills: ["JavaScript"] };
updateSkills(user);

console.log(user.skills); // ["JavaScript", "Node.js"]

Here, user was updated because the function received a reference to the same memory location.


Key Takeaway

  • Primitives → passed by value

  • Objects/arrays → passed by reference copy (so modifications affect the original)


Final Thoughts

JavaScript is always pass by value — but when dealing with objects, the value being passed is actually a reference to the object. Understanding this subtlety helps avoid confusion in interviews and in real-world debugging.