Freeze method in JavaScript

The freeze() method is used to freeze an object.

Freezing an object does not allow adding new properties to an object, prevents from removing and prevents the enumerability, configurability or writability of existing properties i.e It returns the passed object and does not create a frozen copy.

const obj = {
prop: 100

obj.prop = 200;             //Throws an error in strict mode

console.log(obj.prop)   //100

Note: It causes a TypeError if the argument passed is not an object.

What is the purpose of freeze method in JavaScript?

The main benefits of using freeze method:

1. It is used for freezing objects and arrays.
2. It is used to make an object immutable.

Why do I need to use freeze method in JavaScript?

In the Object-oriented paradigm, an existing API contains certain elements that are not intended to be executed, modified or re-used outside of their current context. Hence it works as the final keyword which is used in various languages.

Leave a Comment