JavaScript’s Object.freeze()
and Object.seal()
methods are used to prevent changes to an object. Object.freeze()
creates a read-only object that cannot be modified, while Object.seal()
allows modification of existing properties but preventing adding or removing properties.
Object freeze() creates a read-only object by preventing any changes to its properties. Once an object is frozen, you cannot add, remove or modify its properties, and any attempt to do so will result in an error.
Object seal() on the other hand, allows you to modify existing properties of an object but prevents you from adding or removing properties. Once an object is sealed, you cannot add new properties to it or remove existing ones, but you can modify the values of existing properties.
Additionally, the Object.isFrozen()
method can be used to determine whether an object is frozen or not. and Object.isSealed()
method can be used to determine whether an object is sealed or not.
JavaScript object freeze vs seal examples
Simple example code.
<!DOCTYPE html>
<html>
<body>
<script>
//freeze
const objf = {
prop1: "Hello",
prop2: "World"
};
Object.freeze(objf);
objf.prop1 = "Hi"; // Throws an error
delete objf.prop2; // Throws an error
console.log(objf)
// seal
const objs = {
prop1: "Hello",
prop2: "World"
};
Object.seal(objs);
objs.prop1 = "Hi"; // Allowed
delete objs.prop2; // Throws an error
objs.prop3 = "New property"; // Throws an error
console.log(objs)
</script>
</body>
</html>
Output:
Here is a tabular representation of the differences between Object.freeze()
and Object.seal()
in JavaScript:
Feature | Object.freeze() | Object.seal() |
---|---|---|
Prevents adding new properties | Yes | Yes |
Prevents deleting properties | Yes | Yes |
Prevents modifying property values | Yes | No |
Object.isFrozen() method | Available | Not applicable |
Object.isSealed() method | Not applicable | Available |
Additionally, Object.freeze()
provides the Object.isFrozen()
method to check if an object is frozen, while Object.seal()
provides the Object.isSealed()
method to check if an object is sealed.
Comment if you have any doubts or suggestions on this JS difference topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version