What is Immutability in JavaScript Functional Concepts?

Immutability is a core concept in functional programming that emphasizes the use of data structures that do not change after they are created. In JavaScript, which supports both functional and object-oriented programming paradigms, immutability involves avoiding modifications to existing data and instead creating new data structures with the desired changes.

Key aspects of immutability in JavaScript:

  1. Immutable Data Structures:
    Immutability encourages the use of data structures that cannot be changed once they are created. In JavaScript, primitive types (like numbers and strings) are immutable by nature. However, objects and arrays are mutable, meaning their contents can be modified. To achieve immutability with objects and arrays, new objects or arrays are created with the desired changes, rather than modifying the existing ones.
   // Mutable approach (not immutable)
   let mutableArray = [1, 2, 3];
   mutableArray.push(4); // Modifies the existing array

   // Immutable approach
   let immutableArray = [1, 2, 3];
   let newImmutableArray = [...immutableArray, 4]; // Creates a new array
  1. Avoiding In-Place Changes:
    Immutability discourages in-place changes to data. Methods or functions should not modify the state of existing objects or arrays. Instead, they should create and return new copies with the desired changes.
   // Mutable approach
   let person = { name: 'John', age: 30 };
   person.age = 31; // Modifies the existing object

   // Immutable approach
   let immutablePerson = { name: 'John', age: 30 };
   let newImmutablePerson = { ...immutablePerson, age: 31 }; // Creates a new object
  1. Functional Programming Paradigm:
    Immutability aligns with the principles of functional programming, where functions are pure (free of side effects) and work with immutable data. Functions should not modify external state or have side effects, making the code more predictable and easier to reason about.
   // Mutable approach
   let total = 0;
   function addToTotal(value) {
     total += value; // Modifies external state
   }

   // Immutable approach
   function addToTotalImmutable(currentTotal, value) {
     return currentTotal + value; // Returns a new total without modifying external state
   }
  1. Benefits of Immutability:
  • Predictability: Immutability makes it easier to reason about the behavior of code since data doesn’t change unexpectedly.
  • Debugging: Debugging is simplified because data remains constant, and changes are localized to specific points in the code.
  • Concurrency: Immutability helps avoid race conditions and synchronization issues in concurrent or parallel programming.

While JavaScript is not a purely functional language, incorporating immutability principles into your code can lead to more maintainable, predictable, and bug-resistant applications. Libraries like Immutable.js provide additional tools for working with immutable data structures in JavaScript.

Immutability in functional Concepts is how original data is unchangeable. but function can change the public data.

To understand how immutability works in functional concepts, let’s take a look at what it means to mutate data

Example

let color_lawn = {
 title: "lawn",
 color: "#00FF00",
 rating: 0
}
function rateColor(color, rating) {
 color.rating = rating
 return color
}
console.log(rateColor(color_lawn, 5).rating) // 5
console.log(color_lawn.rating) // 5

in the above example color object is immutable in functional concepts e.g rating has been changed in color object

Immutable example in functional concept

var rateColor = function(color, rating) {
 return Object.assign({}, color, {rating:rating})
}
console.log(rateColor(color_lawn, 5).rating) // 5
console.log(color_lawn.rating) // 4

in the above example. we used Object.assign to change the color rating. Object.assign is the copy machine; it takes a blank object, copies the color to that object, and overwrites the rating on the copy. Now we can have a newly rated color object without having to
change the original

Immutable example in ES6 arrow function :

const rateColor = (color, rating) =>
 ({
 ...color,
 rating
 })

More examples with arrow function

let list = [
 { title: "Rad Red"},
 { title: "Lawn"},
 { title: "Party Pink"}
]

We could create a function that will add colors to that array using Array.push

var addColor = function(title, colors) {
 colors.push({ title: title })
 return colors;
}
console.log(addColor("Glam Green", list).length) // 4
console.log(list.length) 

Array.push is not an immutable function. This addColor function changes
the original array by adding another field to it. In order to keep the colors array
immutable, we must use Array.concat instead

const addColor = (title, array) => array.concat({title})
console.log(addColor("Glam Green", list).length) // 4
console.log(list.length) 

Array.concat concatenates arrays. In this case, it takes a new object, with a new color title, and adds it to a copy of the original array

ES6 spread operator to concatenate arrays in the same way it can be used to copy objects

const addColor = (title, list) => [...list, {title}]

Leave a Comment