How to freeze an Object in JavaScript?

JavascriptObject Oriented ProgrammingProgramming

In the Real time world javascript doesn't have traditional classes as seen in other languages. It has objects and constructors. Object.freeze() is one among many constructor methods helps to freeze an object.

Freezing an object does not allow new properties to be added to the object and also prevents the object from changing its own properties. Object.freeze() will always try to preserve the enumerability, configurability, writability and the prototype of the object. It won't create a frozen copy.


1) freeze() is used for freezing objects and arrays.

2) freeze() is used to make an object immutable.




Live Demo

// an object is created and a value is assigned
   var myObj1 = {
                prop1: 'freezed values can not be changed'

// the created object is freezed
   var myObj2 = Object.freeze(myObj1);

// property of the frozen object is updated
   myObj2.prop1 = 'change the freezed value';

// Displaying the properties of the frozen object -->


freezed values can not be changed

Updated on 30-Jul-2019 22:30:26