The
Object.freeze() method is used to freeze an
object, making it immutable. Once an object is frozen, its properties cannot be added, modified, or removed. Any attempt to modify a frozen object will throw an error or fail silently in strict mode.
Here's an example that demonstrates the usage of `Object.freeze()`:
const user = {
name: "John",
age: 30,
};
Object.freeze(user);
user.name = "Jane"; // Attempt to modify a property
delete user.age; // Attempt to delete a property
console.log(user);
In this example, the `user` object is created with properties `name` and `age`. After calling `Object.freeze(user)`, the object is frozen, and any attempts to modify or delete its properties will have no effect.
When running the code, you will see that the attempt to modify the `name` property to `"Jane"` and delete the `age` property have no impact on the `user` object. The object remains unchanged, and the console will log the original object:
{ name: 'John', age: 30 }
Note that `Object.freeze()` only freezes the top-level properties of an object. If an object has nested properties, those nested objects can still be modified unless they are also frozen using `Object.freeze()`.
It's important to mention that
`Object.freeze()` creates a shallow freeze, meaning that only the object's direct properties are frozen. If the object contains mutable values such as arrays or objects, those values can still be modified. To achieve a deep freeze, where nested objects and arrays are also frozen, you would need to recursively apply `Object.freeze()` to each nested value.