What is `Object.seal()` for?
Topics
JavaScript
Edit on GitHub
TL;DR
Object.seal()
is used to prevent new properties from being added to an object and to mark all existing properties as non-configurable. This means you can still modify the values of existing properties, but you cannot delete them or add new ones.
What is Object.seal()
for?
Object.seal()
is a method in JavaScript that seals an object, preventing new properties from being added to it and marking all existing properties as non-configurable. This means that while you can still modify the values of existing properties, you cannot delete them or add new properties.
Syntax
obj
: The object to be sealed.
Behavior
- Preventing new properties: Once an object is sealed, you cannot add new properties to it.
- Non-configurable properties: All existing properties become non-configurable, meaning you cannot delete them or change their property descriptors (e.g., making them non-writable).
- Modifiable values: You can still change the values of existing properties as long as they are writable.
Example
Use cases
- Data integrity: Ensuring that an object structure remains unchanged, which can be useful in scenarios where the object represents a fixed schema.
- Security: Preventing accidental or malicious modifications to an object, especially in shared or global contexts.
Checking if an object is sealed
You can check if an object is sealed using the Object.isSealed()
method.