In JS, only numbers and strings are immutable. Once a variable has been pointed to a number or string value in memory, that value will never change.
var myNum = 3 myNum + 5 console.log(myNum) // still equals three
Unlike number and strings, objects are mutable in JS and can change state over time. Some build-in methods create a modified copy of an object to be returned, thus preserving the initial state of the object, but others modify the object directly.
var myArray = [1, 2, 3]; var myNewArray = myArray.concat(4); console.log(myArray) // [1,2,3]; console.log(myNewArray) // [1,2,3,4]; myArray.push(4); console.log(myArray) // [1,2,3,4];
Even though objects are mutable, manipulating variables pointing to properties on objects will only change the object state if those property values are mutable themselves. If a variable is pointing to an immutable value, the variable no longer has any association with the original object. For example:
var numArray = [1,2,3]; var zeroIndex = numArray; zeroIndex = “cat” console.log(numArray) // [1,2,3]; var nestedArray = [[1,2], ]; var firstIndex = nestedArray; firstIndex = “cat” console.log(nestedArray) // [[1,2], [“cat”]]
Why does mutability matter?
Immutability is useful in a few different ways. Most notably: it’s safer. When objects are immutable, many different people can be working with the same data without any fear of it being changed in a way they don’t expect. On large projects with many engineers, this is incredibly important. Even on a small project, immutability is helpful because it allows you to check for equality between objects (since objects are just regular values) and track object changes over time. If you’re a JS programmer and you’re interested in playing around with immutable objects, Mori and immutable.js are two third-party libraries enable implementation of persistent data structures.