Object.seal and Object.freeze both methods are used to make the object immutable i.e. further changes to object will not be allowed.
The main difference in freeze and seal is that in Object.freeze() method no changes can be made to the property whereas if an object is sealed then the changes can be made in the existing properties of the object.
In both cases, no new properties can be added to the object.
Object.seal method is used to seal an object which means new properties cannot be added to the object but values of existing properties can be changed as long as they are writable.
To seal an object, we can use the below syntax :
In this example, after the object is sealed, we have updated the name property and it allows us to update because it’s writable. If I delete myObj.name, then console.log it, the object will remain unchanged, it does not delete the property. If strict mode is on then it’s going to give us an error.
If we want to check if an object is sealed or not then we can make use of Object.isSealed() method to find out the object is sealed or not.
console.log(Object.isSealed(myObj)); // Logs true
Object.freeze is used to freeze an object which means new properties cannot be added to the object and existing properties cannot be changed.
In the above example, after freezing the object, we have tried to change the name property. When we do console log of a name then it does not change. In strict mode, changing the name property will throw an error.
We can check if an object is frozen or not with the help of Object.isFrozen() method.
console.log(Object.isFrozen(myObj)); // Logs true
Subscribe to our Youtube channel for more videos :