Is JavaScript pass by value or pass by reference?
JavaScript is always pass by value. For objects, the value passed is a reference, so a function can change the object's contents but cannot make the caller's variable point to a different object.
Explain it simply
Suppose you give a friend a photocopy of your house address. They can go to your house and rearrange the furniture: you will see the change. But if they cross out the address on their photocopy and write a new one, your house does not move.
That is how JavaScript passes arguments:
- Primitives (numbers, strings, booleans): the function gets a copy of the value. Changing it inside does nothing outside.
- Objects and arrays: the function gets a copy of the reference (the address). It can change the object's properties, and the caller sees that. But reassigning the parameter only changes the local copy.
This is sometimes called "call by sharing".
Example
function addBonus(salary) {
salary = salary + 5000;
}
let pay = 30000;
addBonus(pay);
console.log(pay); // Output: 30000
function rename(user) {
user.name = "Priya"; // changes the shared object
}
function replace(user) {
user = { name: "New" }; // only changes the local copy of the reference
}
const u = { name: "Anu" };
rename(u);
console.log(u.name); // Output: Priya
replace(u);
console.log(u.name); // Output: PriyaWhat to say in the interview
"JavaScript is strictly pass by value. With objects, the value that gets copied is a reference. So mutating the object inside a function is visible outside, but reassigning the parameter isn't. That's why some people call it call by sharing. If I don't want a function to mutate my data, I pass a copy, for example with the spread operator or structuredClone."
Common mistakes
- Saying "objects are passed by reference" and then being surprised that reassignment inside the function has no effect outside.