The Object.freeze()
method in JavaScript is used to freeze an object, making it immutable. Once an object is frozen, its properties cannot be added, modified, or removed. This ensures that the object’s state remains unchanged, preventing accidental alterations.
Syntax:
Object.freeze(obj)
Example: Here, the object “obj2” has been assigned property from object “obj1”, and the properties of “obj1” are frozen therefore new properties and values are prevented from being added to “obj2”.
Javascript
// creating an object constructor // and assigning values to it const obj1 = { property1: 'initial_data' };
// creating a second object which will freeze // the properties of the first object const obj2 = Object.freeze(obj1); // Updating the properties of the frozen object obj2.property1 = 'new_data' ;
// Displaying the properties of the frozen object console.log(obj2.property1); |
Output
initial_data