The Object.seal() method seals the given object. This prevents new properties from being added to the object and marks all the existing properties as non-configurable.
Example
seal() Syntax
The syntax of the seal() method is:
Object.seal(obj)
The seal() method, being a static method, is called using the Object class name.
seal() Parameters
The seal() method takes in:
- obj - the object that is to be sealed.
seal() Return Value
The seal() method returns the object being sealed i.e. obj.
Example 1: JavaScript Object.seal()
From the example above, it is clear that we can add, modify, or remove properties from the obj object before it is sealed.
After sealing obj with the seal() method, we
- can modify existing writable properties like foo and value,
- cannot add new properties to obj (attempt fails silently in non-strict mode)
Example 2: Redefine Property After seal()
In the above example, the foo property cannot be redefined as the object is already sealed by the seal() method. Hence, we get a TypeError.
Notes:
- By default, objects are extensible (new properties can be added to them). The sealing of objects makes properties on objects fixed and immutable. The values of present properties can still be changed as long as they are writable.
Object.isSealed()can be used to check if an object is sealed or not.- Attempt to convert data property to accessor or vice versa will fail silently or throw
TypeError.
Recommended Reading: