This page looks best with JavaScript enabled

Don't Update Function Argument Values

 ·   ·  ☕ 2 min read

Do not change those non-primitive function arguments without understanding the significant implications of your action.

Programming languages have pass by reference and pass by value to pass arguments to a function. Javascript passes values for primitives, but references when you are trying to pass objects.

Changing arguments within a function will change the arguments for ever.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
function hello(addressee) {
  addressee.name = "Mr. Anderson";
  return "Hello " + addressee.name;
}

const person = { name: "world" };
console.log(hello(person));
// Hello Mr. Anderson

console.log("person: ", person);
// person:  { name: 'Mr. Anderson' }

It is a disaster if the world is treated as Mr. Anderson.

The simplest way to avoid this is by localizing the object in the function. You can do this with a spread operator or a rest operator.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
function hello({ ...addressee }) {
  addressee.name = "Mr. Anderson";
  return "Hello " + addressee.name;
}

const person = { name: "world" };
console.log(hello(person));
// Hello Mr. Anderson

console.log("person: ", person);
person: {
  name: "world";
}

In the above code we copy the original object and make any changes locally within the function. The changes do not impact the object passed as argument.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things