What does Object.seal() do?
Object.seal() is a built-in JavaScript method that "seals" an object,
forbidding adding or removing properties,
but allowing the values of existing properties to be changed.
It is similar to Object.freeze(), but slightly softer.
In short
Syntax:
javascript
Object.seal(obj)| Argument | Description |
|---|---|
obj | The object to "seal" |
Returns the same object, but with restrictions.
Example
javascript
const user = {
name: 'Tim',
age: 25
};
Object.seal(user);
user.age = 30; // the value can be changed
user.city = 'Berlin'; // cannot add a new one
delete user.name; // cannot delete
console.log(user); // { name: 'Tim', age: 30 }After Object.seal():
- new properties cannot be added;
- existing ones cannot be deleted;
- but the values of existing properties can be changed.
Checking whether an object is sealed
javascript
console.log(Object.isSealed(user)); // trueWhat happens "under the hood"
Object.seal(obj):
- Prevents adding new properties (
Object.preventExtensions(obj)); - Sets
configurable: falsefor all existing properties - they cannot be deleted or have their descriptor changed; - Leaves
writableunchanged - so the values can still be changed.
Example with a descriptor
javascript
const user = { name: 'Tim' };
Object.seal(user);
console.log(Object.getOwnPropertyDescriptor(user, 'name'));Will print:
javascript
{
value: 'Tim',
writable: true,
enumerable: true,
configurable: false
}You can see that configurable: false, while writable stays true.
Comparison with Object.freeze()
| Method | Can change values | Can add | Can delete | Can change descriptors |
|---|---|---|---|---|
Object.preventExtensions() | Yes | No | Yes | Yes |
Object.seal() | Yes | No | No | No |
Object.freeze() | No | No | No | No |
So seal() is an intermediate option between "flexible" and "rigid".
Shallowness (shallow seal)
Object.seal() does not protect nested objects:
javascript
const user = {
name: 'Tim',
address: { city: 'Berlin' }
};
Object.seal(user);
user.address.city = 'Lviv'; // allowed (the nested object isn't sealed)
user.city = 'Warsaw'; // not allowed (a new property)
console.log(user.address.city); // "Lviv"To "seal" the whole tree, you need to do a deep seal recursively.
Example of a deep "seal"
javascript
function deepSeal(obj) {
Object.seal(obj);
for (const key in obj) {
if (typeof obj[key] === 'object' && obj[key] !== null && !Object.isSealed(obj[key])) {
deepSeal(obj[key]);
}
}
return obj;
}Now everything can be "sealed", including nested structures.
SUMMARY
| What it does | Example | Behavior |
|---|---|---|
| "Seals" an object | Object.seal(obj) | Forbids adding and removing properties |
| Can change values | Yes | |
| Can add new properties | No | |
| Can delete properties | No | |
| Check | Object.isSealed(obj) | |
| Depth | Shallow (top level only) |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.