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

Jetbrains image

Is Your CI/CD Server a Prime Target for Attack?

57% of organizations have suffered from a security incident related to DevOps toolchain exposures. It makes sense—CI/CD servers have access to source code, a highly valuable asset. Is yours secure? Check out nine practical tips to protect your CI/CD.

Learn more

Top comments (0)

Jetbrains image

Is Your CI/CD Server a Prime Target for Attack?

57% of organizations have suffered from a security incident related to DevOps toolchain exposures. It makes sense—CI/CD servers have access to source code, a highly valuable asset. Is yours secure? Check out nine practical tips to protect your CI/CD.

Learn more

👋 Kindness is contagious

DEV works best when you're signed in—unlocking a more customized experience with features like dark mode and personalized reading settings!

Okay