To clone, or not to clone

At this point, you may be asking yourself: when am I meant to clone an object, and when is it fine to mutate?

I want to re-emphasise that there is nothing wrong with mutating an object or array, as long as you are aware it is being mutated and nothing else depends on it.

Nevertheless, avoiding mutation is a common theme in functional programming for two primary reasons:

  1. It helps avoid unexpected behaviour.
  2. It stops code having side effects. The term for a function with no side effects is pure.

Example

There is nothing wrong with this code. We need to use the push method to add a new value in an array, and we are aware we are mutating it.

let originalArray = [1, 2, 3];
originalArray.push(4);

But let’s say we put the pushing logic in a function:

function addElementToArray(array, element) {
  array.push(element);
  return array;
}

addElementToArray(originalArray, 4);

It works. But the function now changes something outside of it. Receiving the array as an argument doesn’t help: the genie array points at the same reference rock, which points at the same flying ship. Whoever called this function just had their array changed under their feet.

Better code

function addElementToArray(array, element) {
  return [...array, element];
}

originalArray = addElementToArray(originalArray, 4);

Now our function is clean and pure. It doesn’t affect anything outside of it, and the code that calls it decides whether to keep the new array. Hold on to this idea: it becomes one of the most important rules of the Universal Pattern.