Skip to main content

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)
ArgumentDescription
objThe 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)); // true

What happens "under the hood"

Object.seal(obj):

  1. Prevents adding new properties (Object.preventExtensions(obj));
  2. Sets configurable: false for all existing properties - they cannot be deleted or have their descriptor changed;
  3. Leaves writable unchanged - 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()

MethodCan change valuesCan addCan deleteCan change descriptors
Object.preventExtensions()YesNoYesYes
Object.seal()YesNoNoNo
Object.freeze()NoNoNoNo

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 doesExampleBehavior
"Seals" an objectObject.seal(obj)Forbids adding and removing properties
Can change valuesYes
Can add new propertiesNo
Can delete propertiesNo
CheckObject.isSealed(obj)
DepthShallow (top level only)

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.