The Object.freeze() Method: A Deep Dive
In JavaScript, the freeze() method of the Object object plays a vital role. This method takes an object as an argument and returns the same object with a significant change. The object passed as an argument becomes immutable - meaning that no properties can be added, removed, or modified.
Let’s take a look at an example:
1 | const dog = {} |
In this example, both dog
and myDog
are frozen. The object passed as an argument to Object.freeze() undergoes mutation and cannot be unfrozen. Additionally, since the same object is returned, dog === myDog
evaluates to true.
It is interesting to note that calling Object.freeze() is equivalent to calling Object.preventExtensions() to prevent the object from having additional properties defined. Furthermore, it sets all the properties as non-configurable and non-writable.
To learn more about immutability in JavaScript, you can also refer to the Object.isFrozen() method.
tags: [“JavaScript”, “Object.freeze()”]