Hiprup

What is the difference between pass by value and pass by reference?

How a value is passed into a function depends on its type.

  • Primitives — passed by value: the function gets a copy, so changes inside don't affect the original.

  • Objects & arrays — the reference is passed by value: the function can mutate the shared object, but reassigning the parameter doesn't affect the caller.

Common gotcha: mutating an object argument changes it everywhere — copy it first if you need the original intact.

// Pass by value (primitives)
function changeValue(x) {
  x = 100;  // Changes local copy only
}

let num = 5;
changeValue(num);
console.log(num);  // 5 — unchanged!

// Pass by reference sharing (objects)
function changeProperty(obj) {
  obj.name = 'Jane';  // Modifies the shared object
}

const user = { name: 'John' };
changeProperty(user);
console.log(user.name);  // 'Jane' — changed!

// Reassigning the parameter does NOT affect original
function replaceObject(obj) {
  obj = { name: 'New Object' };  // Replaces local copy of reference
}

const user2 = { name: 'John' };
replaceObject(user2);
console.log(user2.name);  // 'John' — unchanged!
// The original reference still points to the original object

Primitive num is copied — changing x inside the function has no effect on num. Object user's reference is copied — modifying properties through the shared reference affects the original.

Reassigning obj inside replaceObject replaces the local copy of the reference — the original user2 still points to the same object.

Primitives are copied (pass by value). Objects share a reference (pass by reference sharing).

The key gotcha: modifying properties works (shared reference), but reassigning the parameter does not affect the original (reference copy is replaced). Show all three scenarios.