Modes of passing variables

When a function is invoked in JavaScript the arguments in the function can either be passed by value or passed by reference.

Pass By Value

Primitive data types like number, boolean, string, null, undefined are passed by value.

This means that a copy of the actual parameter’s value is made in memory, i.e. the caller and callee have two independent variables with the same value. If the callee modifies the parameter value, the effect is not visible to the caller.

let number = 10;

function increase(x) {
  x = x + 1;
}

increase(number);
console.log(number); // 10

Pass By Reference

On the other hand, complex data types like Arrays and Objects are passed by reference.

Pass by reference means to pass the reference of an argument in the calling function to the corresponding formal parameter of the called function so that a copy of the address of the actual parameter is made in memory, i.e. the caller and the callee use the same variable for the parameter. If the callee modifies the parameter variable, the effect is visible to the caller’s variable.

let counts = { kittens: 0, puppies: 0 };

function addKitten(countObj) {
  countObj.kittens = countObj.kittens + 1;
}

function addPuppy(countObj) {
  const newCounts = countObj;
  newCounts.puppies = newCounts.puppies + 1;
}

console.log(counts);
addKitten(counts);

const otherCounts = counts;
console.log(otherCounts);
addPuppy(otherCounts);
console.log(otherCounts);
console.log(counts);

Can you try seeing if the same thing happens with Arrays?

References

Last updated