DEV Community

Cover image for Immutability and why you need to know its importance!
Nithyanandam Venu
Nithyanandam Venu

Posted on

Immutability and why you need to know its importance!

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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!
Enter fullscreen mode Exit fullscreen mode

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.

Ref: https://www.freecodecamp.org/

Top comments (0)