What is the difference between Object.seal() and Object.freeze() in JavaScript?

JavascriptObject Oriented ProgrammingFront End Technology

The difference between Object.seal() and Object.freeze() is that the former can allow changes to the existing properties of an object whereas the latter won't allow any changes to the object. Object.freeze() makes an object immune to anything, Even minute changes can't be changed.

Object.seal()

Object.seal() method precludes the deletion of an existing property but it can't protect the existing properties from outside changes.

Example

In the following example, because of Object.seal() method the user defined property "prop1" is not deleted despite delete method is applied whereas only the value of property "prop1" is updated.  

Live Demo

<html>
<body>
<script>
   var object1 = {
      prop1: 1
   };
   Object.seal(object1);
   object1.prop1 = 2; // value got changed
   delete object1.prop1;
   document.write(object1.prop1); // it gives value as 2 because of seal.
</script>
</body>
</html>

Output

2


Object.freeze()

In addition to the functionalities of Object.seal(), The Object.freeze() method even wont allow minute changes to the existing properties of an object.

Example

Live Demo

<html>
<body>
<script>
   var object1 = {
      prop1: 1
   };
   Object.freeze(object1);
   object1.prop1 = 2; // value got updated
   delete object1.prop1; // value got deleted
   document.write(object1.prop1); // it gives 1 as output despite value updated to 2
</script>
</body>
</html>

Output

1
raja
Published on 25-Jun-2019 15:35:27
Advertisements