What is Immutability in javascript Functional Concepts ?

.

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

To understand how immutability works in functional concept, 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 example 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