DEV Community

Hidayt Rahman
Hidayt Rahman

Posted on

1 1

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()

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more