How to lock or freeze an object in JavaScript

Home / JavaScript / How to lock or freeze an object in JavaScript


How to lock or freeze an object in JavaScript

This article explains how you can prevent that anything changes to the definition of an object.
Locking or freezing an object can be done with the Object.freeze(obj) method.

Method description

The Object.freeze() method freezes an object: it prevents new properties from being added to it. It also prevents existing properties from being removed and existing properties, or their enumerability, configurability, or writability, from being changed. The method returns the object being frozen.

Important remark

Object.freeze(…) is shallow, this means that object values in a frozen object are still mutable.

Syntax

Parameters

obj

The object to freeze.

return value

The frozen object.

Examples

This is a basic example on the use of Object.freeze

The following example shows that object values in a frozen object can be mutated.

If we want to protect the object and it’s object values, we can use the following function:

Conclusion

In this article we saw that you can protect a JavaScript object so it’s definition cannot be changed anymore. Though it is important to note that the Object.freeze(…) method works shallow, so the values of the frozen object can still be mutated.
Furthermore there is a Object.isFrozen(…) method to test if an object is frozen or not.