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

Classic DEV Post from 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!