const PI = 3.14159265359;
const PI; PI = 3.14159265359;
The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable — just that the identifier cannot be reassigned.
This means that if an object is declared with the const declaration, while the reference cannot be reassigned, the values of the object itself can still be changed.
As can clearly be seen that even though the object was created with const declaration, we were easily able to change the value of one property — name and add a new property altogether — girlfriend.
Declaring an object using const only ensures that the variable i.e.
spidey in this instance, cannot be reassigned to any other value. The contents of the value however (the object in this case) can be altered easily.
To declare a “true constant” object whose contents cannot be altered after its declaration, we must use the Object.freeze() method. Simply speaking, it freezes an object. A frozen object prevents new properties from being added, existing properties from being removed as well as prevents the values of existing properties from being changed.
Let us run the same snippet from above, but this time with Object.freeze().
The frozen object prevented any changes from occuring. The object remained same and the modifications were simply ignored.
To use the strict mode, just write the string
'use strict' at the beginning of your code.
Once in strict mode, any modifications to frozen object will return a TypeError pointing out that the object is not extensible.
But wait a minute …
Is our object truly immutable now ? Let us try this snippet.
Even after using the strict mode and declaring the object with Object.freeze(), we were still able to modify the objects inside our root object. That is because Object.freeze() only freezes the properties of the given object. It does not freeze the objects/arrays that were present inside it as values. This is hence known as a shallow freeze.
In order to permanently lock the properties of our given object, we must freeze our object as well as all the objects/arrays that are present inside it recursively.
Let us write a function to do that.
Now let us try freezing our object using this deepFreeze function and check if it works properly.
Our code throws a TypeError exception which prevents any modifications to the inner objects.
Full code here.
Happy Coding !