DEV Community

Cover image for Object.freeze( ) in JavaScript
Shiva Aryal
Shiva Aryal

Posted on

Object.freeze( ) in JavaScript

In the JavaScript world we already know how the classes and objects are important. Among the Object constructor methods, the Object.freeze() method helps to freeze an object or arrays. Freezing an object does not allow to change any properties from the object. It returns the passed object and does not create a frozen copy.

Frozen object can be prevents from:

  • Adding new properties to the object.
  • Removing or altering existing properties from the object.
  • Preserves the enumerability, configurability, writability and the prototype of the object
  • Changing values of the existing object properties and prototype.

The syntax is:

Object.freeze(obj)
Enter fullscreen mode Exit fullscreen mode

where the obj is the object which has to be freezed.

Example:

Input : const obj = { name: 'initial_name'};
        const newObj = Object.freeze(obj);
        newObj.name = 'new_name';
        console.log(newObj.name);

Output : "initial_name"
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
smrpdl1991 profile image
smrpdl1991

nice one !!