2 min read

Pass by Value vs. Pass by Reference

In JavaScript, understanding how data is passed to functions is crucial for avoiding side effects and bugs. JavaScript is technically always pass-by-value, but the "value" of an object is a reference.

1. Primitives: Pass by Value

Primitive types (String, Number, Boolean, null, undefined, Symbol) are passed by value. A copy of the value is created and passed to the function. Modifying the variable inside the function does not affect the original variable.

let a = 10;

function changeValue(val) {
  val = 20;
  console.log("Inside:", val); // 20
}

changeValue(a);
console.log("Outside:", a); // 10

2. Objects: Pass by Reference (Value of Reference)

Reference types (Objects, Arrays, Functions) are stored in the heap, and the variable holds a pointer (reference) to that location. When you pass an object to a function, you are passing a copy of that reference.

Mutating the Object

Since the copy points to the same object in memory, modifying properties affects the original object.

const person = { name: "Alice" };

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

changeName(person);
console.log(person.name); // "Bob"

Reassigning the Reference

If you reassign the variable completely inside the function, you are changing the local copy of the reference to point to a new object. This does not affect the original object.

let person = { name: "Alice" };

function changePerson(obj) {
  // obj now points to a new memory location
  obj = { name: "Bob" }; 
}

changePerson(person);
console.log(person.name); // "Alice"

3. Summary

  • Primitives: The value itself is passed. Changes are local.
  • Objects: A reference to the object is passed.
    • Modifying properties changes the original.
    • Reassigning the variable does not change the original.

programming/javascript/vanilla/javascript programming/javascript/vanilla/data-types