Skip to main content

Pass by value and reference

In JavaScript, when you pass a variable to a function, you are passing a copy of the variable's value, not the variable itself. This concept is known as pass by value.

However, when you pass an object to a function, you are passing a reference to the object in memory, not a copy of the object itself. This concept is known as pass by reference.

Pass by value

When you pass a primitive value to a function, a copy of the value is created in memory, and the function works with this copy. The original value remains unchanged.


function changeValue(x) {
x = 10;
console.log(x); // Output: 10
}

let num = 5;
changeValue(num);
console.log(num); // Output: 5

Pass by Reference

When you pass an object to a function, you are passing a reference to the object in memory.

This means that the function can modify the object's properties directly, and the changes will be reflected outside the function.

function changeObject(obj) {
obj.name = "John";
console.log("Inside function: ", obj); // { name: "John" }
}

let person = { name: "Jane" };
changeObject(person);
console.log("Outside function: ", person); // { name: "John" }

Summary

  • Pass by value. When you pass a primitive value to a function, a copy of the value is created in memory, and the function works with this copy. The original value remains unchanged.
  • Pass by reference. When you pass an object to a function, you are passing a reference to the object in memory. This means that the function can modify the object's properties directly, and the changes will be reflected outside the function.

References