JavaScript Object.seal(obj) method
The Object.seal(obj)
method in JavaScript is used to seal an object, which means that it prevents new properties from being added to the object and marks all existing properties as non-configurable. However, it allows existing properties to be modified or deleted. This method is useful for ensuring that the structure of an object remains the same while still allowing changes to its values.
Syntax:
Parameters:
obj
: The object you want to seal. This object is passed by reference.
Return Value:
- The sealed object itself.
Key Features:
- Preventing Additions: After an object is sealed, no new properties can be added to it.
- Non-Configurable Properties: All existing properties become non-configurable. This means that you cannot change the descriptor of any property (e.g., making a property non-enumerable).
- Modifiable Properties: Existing properties can still be modified (i.e., their values can be changed) and deleted, unless they are marked as non-writable.
- Shallow Sealing: Like
Object.freeze()
,Object.seal()
only affects the immediate properties of the object. If the object contains nested objects, those nested objects are not sealed automatically.
Example 1: Basic Usage
In this example, after sealing the obj
, the age
property can still be modified, but new properties cannot be added and existing properties cannot be deleted.
Example 2: Checking if an Object is Sealed
You can check if an object is sealed using Object.isSealed()
:
In this case, Object.isSealed(obj)
returns true
because the object has been sealed.
Example 3: Sealing an Array
You can also use Object.seal()
on arrays:
In this example, the array is sealed, so you can modify the values, but you cannot change the array structure in terms of property descriptors.
Summary:
Object.seal(obj)
is a method that seals an object, making it non-extensible while allowing existing properties to be modified.- It prevents new properties from being added and marks all existing properties as non-configurable.
- Understanding how to use
Object.seal()
is important for scenarios where you want to maintain the structure of an object while allowing for some level of flexibility in its property values.