What does immutability really mean in JavaScript?
The concept of immutability is a funny one.
In one translation, it can mean unchanging — however, setting something up as a let
or var
and then not allowing it to change might as well be as good as using const
There are a lot of people who take this translation a bit too far in its application, and as a result, misunderstand the concept and depth of immutability.
In this piece, I’ll be decrypting the idea of immutability and how it is applied in JavaScript.
Let’s look at the meaning of immutability
The word immutability has its origins in Latin and means “not changeable”. Its official synonym is “changeless” and when applied to computer programming, the idea is pretty much the same.
However, this application is often oversimplified. Many developers associate immutability with the inability to change anything at all.
For example:
var cat = "Tibbers";
cat = "Tibbles";
According to the incorrect application of the concept, the above example is regarded as a violation of immutability.
It is incorrect because there is more to immutability than not changing a particular value. Immutability functions deeper than just forcing you to keep values exactly the same.
Developers often get confused because if immutability equates to “don’t change things”, then why not just use const
?
This skepticism is valid and for a long time, I questioned this logic too.
What exactly is immutability?
When it comes to object-oriented and functional programming, the concept of immutability is applied at the object level.
It’s to do with the state and how you’re not allowed to modify after it’s been created. Every language has its own system of state management and before we go any further, we need to understand exactly what a state is.
In object-oriented, a state has two parts to it — the properties and the values. The properties are generally static, meaning that they don’t change. The values, however, are expected to be dynamic and therefore changeable.