In JavaScript, how data is passed to a function depends on the type of value.JavaScript is technically pass-by-value, but objects behave like pass-by-reference.

1.Primitive Types → Passed by Value

Primitive types in JavaScript:

  • Number
  • String
  • Boolean
  • undefined
  • null
  • Symbol
  • BigInt

Example: Number

let x = 10;

function change(val) {
val = 20;
}

change(x);
console.log(x); // 10 (unchanged)

✔ A copy of 10 is passed
✔ Original value remains unchanged

Example: String

let name = "Zaman";

function update(str) {
str = "Ahmed";
}

update(name);
console.log(name); // "Zaman"

✔ Strings are immutable
✔ Passed by value

2.Objects & Arrays → Passed by Reference Value

Objects, arrays, and functions are non-primitive types.

⚠️ JavaScript passes the reference (address) by value.

Example: Object

let user = { name: "Zaman" }; 
function update(obj) { 
obj.name = "Ahmed"; 
} 
update(user); 
console.log(user.name); // "Ahmed"

✔ Both point to the same object
✔ Changes affect original

Example: Array

let numbers = [1, 2, 3];

function add(arr) {
arr.push(4);
}

add(numbers);
console.log(numbers); // [1, 2, 3, 4]

✔ Same array reference is used

3.Reassigning Object Reference (Important!)

let user = { name: "Zaman" }; 
function change(obj) { 
obj = { name: "Ahmed" 
}; 
} 
change(user); 
console.log(user.name); // "Zaman"

❗ Why?

✔ Only the reference copy was changed
✔ Original reference remains unchanged

4.Visual Explanation (Conceptual)

Primitive

x = 10
copy → 10

Object

user → reference → { name: "Zaman" }
copy of reference → same object

5.Functions Are Objects Too

function test() {}

function modify(fn) {
fn.newProp = "added";
}

modify(test);
console.log(test.newProp); // "added"

✔ Functions behave like objects
✔ Passed by reference value

6.How to Avoid Mutation (Create Copies)

Object Copy (Shallow)

function safeUpdate(obj) {
let copy = { ...obj };
copy.name = "Ahmed";
return copy;
}

Array Copy

function addSafe(arr) {
return [...arr, 4];
}

7.Deep Copy (Important)

Shallow copy fails for nested objects.

Using structuredClone() (Modern)

let original = { a: { b: 1 } };
let copy = structuredClone(original);copy.a.b = 2;
console.log(original.a.b); // 1

Using JSON (Limitations)

let copy = JSON.parse(JSON.stringify(obj));

❌ Loses functions, dates, undefined

Categorized in:

Javascript,