On Immutability

Immutability in Javascript

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.
For example:

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.
For example:

var myArray = [1, 2, 3];  
var myNewArray = myArray.concat(4);  
console.log(myArray) // [1,2,3];  
console.log(myNewArray) // [1,2,3,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[0];  
zeroIndex = “cat”  
console.log(numArray) // [1,2,3];

var nestedArray = [[1,2], [3]];  
var firstIndex = nestedArray[1];  
firstIndex[0] = “cat”  
console.log(nestedArray) // [[1,2], [“cat”]]  
Why does mutability matter?

Mutability has some advantages, although they are probably not as important as some might expect. First, mutable objects are explicitly more space efficient since they can be changed once they are committed to memory rather than having to be copied over every time we want to do anything. Likewise, mutability allows for higher GC efficiency since the interpreter doesn’t need to be concerned with clearing out all the copies that are no longer used. That being said, functional programming languages avoid the space-complexity pitfall by implementing immutable objects using “structural sharing” via hash map and vector tries. If you’re interested, you can read about that here, but the punchline is that space is not a huge issue even in languages where absolutely everything is immutable. Furthermore, Google’s V8 JavaScript engine has such an robust GC system that GC efficiency isn’t a huge problem either.

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.