How to use Object.freeze() Method In Javascript
JavaScript Object.freeze() method is used to freeze an object. Freezing an object does not allow new properties to be added to the object and prevents removing or altering the existing properties.
Syntax:
Object.freeze( obj );
Example: In this example, we will use Object.freeze() method to make the object immutable.
Javascript
// Creating an object constructor and assigning // values to it const obj = { name: 'JavaScript' }; // Creating immutable object using freeze method Object.freeze(obj); // Updating the properties of the frozen object obj.name = 'HTML' // Displaying the properties of the frozen object console.log(obj.name); |
JavaScript
The output clearly shows when the object is passed in the object.freeze() method it becomes immutable and canât be modified.
How to Preserve Immutability of Objects in JavaScript ?
Immutability is an issue when it comes to private or restricted objects. Sometimes we need to create new objects without making modifications or changes unintendedly to preserve the integrity of data. Thatâs why, we need to find a way to preserve the object states. In this article, we will understand the immutability of objects concept, along with understanding the different approaches to preserving the immutability of objects & correspondingly will know their basic implementation with the help of examples.
Contact Us