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. It prevents from deletion of existing properties but cannot prevent them from external changes.
- Object.freeze() does not allow so. It makes an object immune to everything even little changes cannot be made.
Syntax:
Object.seal(objectname);
Object.freeze(objectname);
Example 1: This example, 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.
javascript
let obj = {
value: 10
};
Object.seal(obj);
obj.value = 20;
console.log(obj.value);
|
Output:
20
Example 2: This example, 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.
javascript
let obj = {
value: 10
};
Object.freeze(obj);
obj.value = 20;
console.log(obj.value);
|
Output:
10
Let us see the differences in a tabular form:
It is used to prevent the object from adding new properties |
It is used to make the properties of an object non-configurable. |
It is also used so that the current existing properties should not be modified |
It is also used so that the new properties do not get added |
It takes a parameter as an object |
It takes parameters as an object |
Its return type is of the object type. |
Its return type is e-sealed object type. |
Last Updated :
21 Jul, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...