Understanding Pass-By-Value in JavaScript

📌 What Does "Pass-By-Value" Mean?

In JavaScript, when you pass a variable into a function, you're either passing the value itself or a reference to the value. In the case of primitive types (like numbers, strings, booleans, etc.), JavaScript uses pass-by-value.

Note

💡 The term "pass-by-value" means a copy of the variable's value is passed to the function. Changes made inside the function do not affect the original variable.

🧪 Example: Pass-by-Value with Primitives

Primitive Example

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

let num = 10;
modify(num);
console.log("Outside function:", num);

🔍 Even though we added 5 inside the function, the original variable num remains unchanged outside. That's because only a copy of the value 10 was passed to the function.

🎯 How It Works

  • Primitive types (number, string, boolean, null, undefined, symbol, bigint) are passed by value
  • When passed to a function, JavaScript creates a copy of the value
  • Modifying the parameter doesn’t affect the original variable

🧠 Visualizing the Concept

Media content

In pass-by-value, the function receives a copy 🧾 — not the original. Any change affects only that copy.

🔁 Common Misconception

Many developers get confused because objects and arrays behave differently. These are passed by reference — meaning the function receives a reference to the same object in memory.

Objects Are Not Passed by Value

function changePerson(obj) {
  obj.name = "Bob";
}

const person = { name: "Alice" };
changePerson(person);
console.log(person.name); // Bob 😱

Note

⚠️ Be careful: non-primitives like objects and arrays are not passed by value.

✅ Summary

  • 🧾 Primitives (string, number, boolean, etc.) are passed by value
  • 🧠 Functions get a copy of the value, not the original
  • 🔒 The original variable remains unchanged inside the function

📚 References

>>“In JavaScript, values travel alone — they don’t carry the original behind them.” 🎒