Immutability is a popular concept not just in JavaScript, but most programming languages in general. The reason behind this of course is functional programming which gives software developers a brand new paradigm to utilize when coding. Let’s dive into the details of mutability and immutability.
What is Mutability?
A mutable value is one that can be changed without creating an entirely new value. In JavaScript, objects and arrays are mutable by default, but primitive values are not. Once a primitive value is created, it cannot be changed, although the variable that holds it may be reassigned. There is nothing wrong with mutability. Take a look at the code below:
const dog = {
name: 'turtle',
age: 10
}
// Make a copy of dog object
const newDog = dog;
// Changing the age of the new dog
newDog.age = 12;
console.log(newDog === dog); // true
As you can see, we’re copying the object to another object and changing the dogs age. The problem is that the change happens everywhere.
This happens because the object is a reference type. Change it in one place and it is changed everywhere due to it being tied in the same memory location.
const newDog = dog
Since you are copying the reference (and not the real values), both values change.
Immutability in Object
The main objective of immutability is the object should not change and should create a new object.
const dog = {
name: 'turtle',
age: 10
}
const newDog = { ...dog, age: 12 }
console.log(newDog === dog); // false
We use the spread operator to copy all of the properties and create an entirely different object. Immutability is about maintaining the state of an object and making development simple. The whole idea is an update should not change the object but create a new object with entirely new data.
Immutability in Arrays
Arrays work very similar to objects and you can also use the spread operator.
const dogs = [ 'corgi', 'frenchi' ];
const newDogs = [ ...dogs, 'labradoodle' ];
console.log(dogs === newDogs) // false
console.log(dogs) // [ 'corgi', 'frenchi' ];
console.log(newDogs) // [ 'corgi', 'frenchi', 'labradoodle' ];