Immutability, defined in a single line, means that once that value is assigned, then it can never be changed:
var string1 = "I am an immutable"; var string2 = string1.slice(4, 8);
string1.slice
does not change the value of string1
. In fact, no string methods change the string they operate on, they all return new strings. The reason is that strings are immutable—they cannot change.
Strings are not the only immutable entity in JavaScript. Numbers, too, are immutable.
Earlier, we saw that even if you create objects with const
in front of them, a programmer is still able to modify its properties. This is because const
creates an immutable binding, that is, you cannot assign a new value to the binding.
Therefore, in order to truly make objects constants (that is, unmodifiable properties), we have to use something called Object.freeze
. However, Object.freeze
is, again, a shallow method, that is, you need to recursively apply it on nested objects to protect them. Let's clear this up with a simple example.
Consider this example:
var ob1 = {
prop1 : 1,
prop2 : {
prop2_1 : 2
}
};
Object.freeze( ob1 );
const ob2 = {
prop1 : 1,
prop2 : {
prop2_1 : 2
}
}
ob1.prop1 = 4; // (frozen) ob1.prop1 is not modified
ob2.prop1 = 4; // (const) ob2.foo gets modified
ob1.prop2.prop2_1 = 4; // (frozen) modified, because ob1.prop2.prop2_1 is nested
ob2.bar.value = 4; // (const) modified
ob1.prop2 = 4; // (frozen) not modified, bar is a key of obj1
ob2.prop2 = 4; // (const) modified
ob1 = {}; // (frozen) ob1 redeclared (ob1's declaration is not frozen)
ob2 = {}; // (const) ob2 not redeclared (used const)
We froze ob1
so all of its first-level hierarchical properties got frozen (that is, cannot be modified). A frozen object will not throw an error when attempted to be modified, but rather it'll simply ignore the modification done.
However, as we go deeper, you'll observe that ob1.bar.value
got modified because it's 2 levels down and is not frozen. So, you'll need to recursively freeze nested objects in order to make them constant.
Finally, if we look at the last two lines, you'll realize when to use Object.freeze
and when to use const
. The const
declaration is not declared again, whereas ob1
is redeclared because it's not constant (it's var
). Object.freeze
does not freeze the original variable binding and hence is not a replacement for const
. Similarly, const
does not freeze properties and is not a replacement for Object.freeze
.