What is Object.seal()?
Object.seal() is a JavaScript method that seals an object, preventing new properties from being added to it and marking all existing properties as non-configurable. This means you cannot delete existing properties or change their enumerability, configurability, or writability attributes. However, you can still change the values of existing writable properties.
What Object.seal() Does
When an object is sealed using Object.seal(), the following restrictions apply:
- New properties cannot be added to the object.
- Existing properties cannot be deleted from the object.
- The configurable attribute of existing properties is set to
false, meaning their property descriptors (likewritable,enumerable,configurable) cannot be changed. - The values of existing writable properties can still be changed.
An object that is sealed is also non-extensible (meaning Object.isExtensible() will return false for it).
Syntax
Object.seal(obj)
Where obj is the object to be sealed.
Return Value
The method returns the object that was passed in.
Example
const myObject = {
a: 10,
b: 'hello'
};
Object.seal(myObject);
console.log(Object.isSealed(myObject)); // true
// Try to add a new property
myObject.c = 30; // Ignored in non-strict mode, throws TypeError in strict mode
console.log(myObject.c); // undefined
// Try to delete an existing property
delete myObject.a; // Ignored in non-strict mode, throws TypeError in strict mode
console.log(myObject.a); // 10
// Try to modify an existing property's value (allowed)
myObject.b = 'world';
console.log(myObject.b); // 'world'
// Try to redefine a property's attributes (not allowed)
// Object.defineProperty(myObject, 'b', { writable: false }); // Throws TypeError
Key Characteristics
- Adding properties: Not allowed.
- Deleting properties: Not allowed.
- Modifying property values: Allowed for existing writable properties.
- Modifying property attributes (e.g.,
writable,enumerable,configurable): Not allowed, asconfigurableis set tofalsefor all existing properties.
Comparing with Other Object Methods
| Method | Add Properties | Delete Properties | Modify Values | Modify Attributes |
|---|---|---|---|---|
| Object.preventExtensions() | No | Yes | Yes | Yes |
| Object.seal() | No | No | Yes | No (sets configurable to false) |
| Object.freeze() | No | No | No | No (sets configurable and writable to false) |
Use Cases
Object.seal() is useful when you want to ensure that the structure of an object remains constant – no new keys are added, and no existing keys are removed – but you still need the flexibility to update the values associated with those keys. This is particularly valuable for configuration objects or state objects where the available settings are fixed, but their current values might change during runtime.