What is `Object.freeze()` for?
Topics
JavaScript
Edit on GitHub
TL;DR
Object.freeze()
is used to make an object immutable. Once an object is frozen, you cannot add, remove, or modify its properties. This is useful for creating constants or ensuring that an object remains unchanged throughout the program.
What is Object.freeze()
for?
Object.freeze()
is a method in JavaScript that prevents modification of existing property values and the addition or removal of properties from an object. This method is useful for creating immutable objects, which can help in maintaining the integrity of data and avoiding unintended side effects.
How to use Object.freeze()
To use Object.freeze()
, simply pass the object you want to freeze as an argument to the method. Here is a basic example:
Characteristics of a frozen object
- Immutability: Once an object is frozen, its properties cannot be changed, added, or removed.
- Non-extensible: A frozen object is also non-extensible, meaning you cannot add new properties to it.
- Non-configurable: The properties of a frozen object become non-configurable, meaning you cannot change property descriptors.
Use cases for Object.freeze()
- Constants: When you want to create a constant object that should not be modified.
- Data integrity: Ensuring that an object remains unchanged throughout the lifecycle of an application.
- Security: Preventing accidental or malicious changes to critical objects.
Limitations
Object.freeze()
only makes the object itself immutable. If the object contains nested objects, those nested objects are not frozen and can still be modified.- To deeply freeze an object, you would need to recursively apply
Object.freeze()
to all nested objects.