Immutability and why you need to know its importance!
Nithyanandam Venu
Posted on March 14, 2024
If you are working with javascript, you must give a lot of importance to the immutability.
What is immutability?
Immutable means something that cannot be changed. In programming, immutable is used to describe a value that cannot be changed after it's been set. But do you know Primitives in JavaScript: Naturally Immutable! specifically, arrays and objects that we commonly use.
Why it matters?
Let's see with a simple example. (kept the example very naive to showcase the impact of immutability, in real time you would be passing around your objects more than you imagine knowingly or unknowingly!)
let person = {name:"John", age: 30};
const original = () => {
console.log(person.name,person.age)
}
original() // prints john,30
Now let's assume, we have another function where I want to just change the name for another person and print.
let person = {name:"John", age: 30};
const original = () => {
console.log(person.name,person.age)
}
original() // prints john,30
const newPerson = (newsperson) {
person.name = 'jake';
console.log(newsperson.name,newsperson.age)
}
pass(person) //print jake,40
what would the original() function print now? *john,30, or Jake,40.
orginal() //it would print jake,40 as well *
Because of the immutable nature of the object. If you pass around your data in objects and array lot over your application without worrying about immutability, trust me you are going to headache on where your original values got changed.
The simplest way to overcome is this to take a copy of the object. It can be a deep clone or shallow based on your need.
const newPerson = (newsperson) {
person.name = 'jake';
console.log(newsperson.name,newsperson.age)
}
pass(...person) //taking clone of the object instead of direct reference so orignal object remains same!
Why Is Immutability Important?
- Once an immutable value is set, it isn't changed. Rather a new value is created. This makes the value predictable and consistent throughout the code. So it aids in managing the state throughout the application. Plus immutability is a key principle in state management frameworks, such as Redux.
- Code becomes simpler and less error-prone when data structures don't change unexpectedly. This also simplifies debugging and maintenance.
- Embracing immutability is in line with functional programming principles, leading to fewer side effects and more predictable code.
I hope now you get the picture of why immutability is very important to keep your code predictable and adhere to the functional programming principle and mainly to avoid unwanted debugging headaches.
Posted on March 14, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.