JavaScript Object.freeze(obj) method
The Object.freeze(obj)
method in JavaScript is used to freeze an object, which means that it prevents any modifications to the object. Once an object is frozen, you cannot add, delete, or modify its properties. This method is useful for creating immutable objects.
Syntax:
Parameters:
obj
: The object you want to freeze. This object is passed by reference.
Return Value:
- The frozen object itself.
Key Features:
- Immutable Properties: After an object is frozen, its properties cannot be changed (neither values nor types).
- Preventing Additions/Deletions: You cannot add new properties or delete existing properties from a frozen object.
- Shallow Freezing:
Object.freeze()
performs a shallow freeze. This means that if the object has nested objects (objects as property values), those nested objects are not frozen automatically; only the top-level properties are frozen. You would need to recursively freeze nested objects if immutability is desired throughout. - Non-Enumerable and Non-Configurable Properties: Any non-enumerable or non-configurable properties of the object will remain unchanged, but they will also be frozen.
Example 1: Basic Usage
In this example, after freezing the obj
, attempts to modify, add, or delete properties have no effect.
Example 2: Shallow Freezing
In this example, the address
property is not frozen, so its nested property city
can still be modified. This demonstrates that Object.freeze()
only freezes the top-level properties.
Example 3: Checking If an Object is Frozen
You can check if an object is frozen using Object.isFrozen()
:
In this example, Object.isFrozen(obj)
returns true
because the object has been frozen.
Example 4: Freezing an Array
You can also use Object.freeze()
on arrays:
In this case, the array is frozen, and attempts to modify it through methods like push()
will have no effect.
Summary:
Object.freeze(obj)
is a method that freezes an object, making it immutable at the top level.- It prevents any changes to the object’s properties, including additions, deletions, and modifications.
- Understanding how to use
Object.freeze()
is important when you need to ensure that an object remains unchanged throughout your application, particularly in functional programming or when working with configurations.