If we want an object to be immutable i.e. not change by programmer accidentally or willingly,
Object.freeze is the solution.
Object.freeze is a shallow freeze so the nested objects need to be frozen using recursion.
Say we have following
person object that we want to freeze
We can freeze the person object using
Object.freeze as follows
Now, if we try to add a new property on
person object say
gender it will fail silently
person object again we would get the original object.
The value of the existing properties is also frozen. Let’s try to change the
Again, if we log the value we still get the original object
We can check whether the object is frozen or not using
Object.isFrozen(). It returns boolean value i.e. true or false