DEV Community

Hidayt Rahman
Hidayt Rahman

Posted on

Make Object readOnly by using Object.freeze()

The Object.freeze() method freezes an object. A frozen object can no longer be changed; freezing an object prevents new properties from being added to it, existing properties from being removed, prevents changing the enumerability, configurability, or writability of existing properties, and prevents the values of existing properties from being changed. In addition, freezing an object also prevents its prototype from being changed. freeze() returns the same object that was passed in.

Create an abject

const person = {
  name: "hidayt",
  location: "delhi"
}
Enter fullscreen mode Exit fullscreen mode

Add Object.freeze() method just after it.


// restriction
Object.freeze(person);
Enter fullscreen mode Exit fullscreen mode

Try to update location property of the object and log it


// update location
person.location = "Mumbai";

console.log(person.location); // delhi
Enter fullscreen mode Exit fullscreen mode

Yes, It will not allow to update the object.

Note: Always put Object.freeze() after the object, Which you want to restrict and pass that object into the freeze() method.

Ref: Object.freeze()

Top comments (0)