What is the difference between freeze and seal in JavaScript ?
Both freeze and seal are used to create non extensible objects in JavaScript, but there are plenty of differences between them. Object.seal() allows changes to the existing properties of an object whereas Object.freeze() does not allow so. Object.freeze() makes an object immune to everything even little changes cannot be made. Object.seal() prevents from deletion of existing properties but cannot prevent them from external changes. Syntax:
Object.freeze(objectname);
Example 1: Depicts implementation of Object.seal().
javascript
<script> // creates an object var obj = { // assigns 10 to value value: 10 }; // creates a non-extensible object Object.seal(obj); // the value gets updated to 20 obj.value = 20; console.log(obj.value); </script> |
Output:
20
Example-1 depicts how Object.seal() is used to create a non-extensible object, but that does not prevent the value of the object to be changed and it is seen that the value gets updated to 20. Syntax:
Object.seal(objectname);
Example 2: Depicts implementation of Object.freeze().
javascript
<script> // creates an object var obj = { // assigns 10 to value value: 10 }; // creates a non-extensible object Object.freeze(obj); // updates the value obj.value = 20; // but cannot change the existing value console.log(obj.value); </script> |
Output:
10
Example-2 depicts how Object.freeze() is used to create a non-extensible object, but where the existing value of the object is prevented from being changed and 10 is given as the output.
Let us see the differences in a tabular form -:
freeze | seal | |
1. | freeze() is a javascript object which is used to prevent the object from adding new properties | seal() is a Javascript method which is used to make properties of an object non-configurable. |
2. | It is also used so that the current existing properties should not be modified | It is also used so that the new properties does not gets added |
3. |
Its syntax is -: Object.freeze(object) |
Its syntax is -: Object.seal(object) |
4. | It takes a parameter as an object | It takes parameters as an object |
5. | Its return type is of the object type. | Its return type is of the sealed object type. |
6. |
Its supported browsers are -: Chrome , Internet Explorer, Safari, Microsoft Edge, Opera Firefox |
Its supported browsers are -: Chrome , Internet Explorer, Safari, Microsoft Edge, Opera, Firefox |