Concept of Immutability
When you are developing our applications, might end up in some situations where you want to create a new object in our code, containing a new property or value while also maintaining the original value. The concept of immutability can help us to create new objects, making sure that we’re not changing the original value.
Simple example code created two variables and assigned the
myAge to the
myNewAge variable. But after we changed the value of
myAge, we will see that they’re not the same.
<!DOCTYPE html> <html> <body> <script> let myAge = "22"; let myNewAge = myAge; myAge = "23"; console.log(myAge === myNewAge); </script> </body> </html>
Primitive values cannot be changed by reassignment.
var str = "testing"; var str = "testing,testing"; console.log(str); // testing, testing
But object can
var fruits = ["apple", "banana", "orange"]; fruits = "mango"; console.log(fruits); //["mango", "banana", "orange"]
Do comment if you have any doubts or suggestions on this JS immutable topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version