Why you shouldn't mutate parameters


  Hey there! This article is being published a "work in progress," which means that it is not done. So take everything with a grain of salt.

I may or may not come back and finish this article. Regardless, I hope that it's helpful in its current state.

When you pass an argument to a function, you can then access it as a parameter within the function.

Value arguments #

When you pass a value argument like 2, true, or hello, you have access to that value within the function. As a result, you can mutate it like so:

function double(number) {
number = number * 2
return number
}

double(2) // 4
  1. A value, or
  2. A reference to a value?

Mutating parameters #

When you pass a variable as an argument, you are handing a reference to the function – not a value. So when the function references its parameter, JavaScript traces the reference chain to the stored value.

Let’s look at an example:

let colors = ['red', 'orange', 'yellow', 'green']

let warmColors = remove(colors, 3) // 'green' is not a warm color

function remove(array, index) {
// 🎗 Remember: [] === [] is false
console.log(array === colors)
}

What would you expect the console output to be? You might be surprised to see that the log is true. That’s because we passed a reference to colors and not the value.

So if we go on to mutate the array parameter, we will make changes to the value that it and colors reference:

let colors = ['red', 'orange', 'yellow', 'green']

let warmColors = remove(colors, 3)

function remove(array, index) {
array.splice(index)
return array
}

console.log(colors)
console.log(warmColors)

The log after running our remove() function shows that colors has been modified:

[ 'red', 'orange', 'yellow' ]
[ 'red', 'orange', 'yellow' ]

About

My name is Sean McPherson (SeanMcP), and I am a software engineer based in Pittsburgh, PA. Here I write articles about programming for developers of all levels.