Dmytro Morar
JavaScript

By Value vs By Reference

In JavaScript, all arguments are passed by value, but if the value is a reference to an object, the function receives a copy of that reference. Therefore, primitives do not change, but objects can be modified through the shared reference.

Call by Value

  • A copy of the value itself is passed (number, string, boolean, null, undefined, symbol, bigint).
  • Changes inside the function do not affect the original, as the function works with its local copy.
function modifyPrimitive(num) {
  num = num + 10;
  console.log("Inside:", num); // 20
}

let value = 10;
modifyPrimitive(value);
console.log("Outside:", value); // 10

Primitives are immutable and are passed as a separate value.

Call by Reference

  • A copy of the reference to the object (object, array, function) is passed.
  • Both identifiers point to the same object in memory.
  • Changing properties is reflected outside, but reassigning the reference does not affect the original.
function modifyObject(obj) {
  obj.name = "Jane";
  console.log("Inside modify:", obj); // { name: 'Jane', age: 30 }
}

let person = { name: "John", age: 30 };
modifyObject(person);
console.log("Outside:", person); // { name: 'Jane', age: 30 }

function reassignObject(obj) {
  obj = { city: "New York" };
  console.log("Inside reassign:", obj); // { city: 'New York' }
}

let data = { country: "USA" };
reassignObject(data);
console.log("Outside:", data); // { country: 'USA' }

Internal property modification is preserved, but reassigning the object inside the function does not affect the external variable.

Key Ideas

  • Primitives → copied by value, isolated from the original.
  • Objects → the reference is copied, pointing to the same place in memory.
  • Changes through the reference are visible outside, but changing the reference inside the function does not change the original.
  • A correct understanding of this difference is critical when working with mutable data structures.

Links

https://daveceddia.com/javascript-references/

On this page