What is `Object.seal()` for?
TL;DR
Object.seal() prevents extensions and makes every existing own property non-configurable. Existing data-property values can still change when their descriptors are writable. The operation is shallow: nested objects are unaffected. Invalid additions and deletions throw in strict mode and may fail silently otherwise. Sealing is useful for catching accidental shape changes, not for enforcing authorization or protecting secrets.
// 'use strict'const obj = { name: 'John' };Object.seal(obj);obj.name = 'Jane'; // Allowedobj.age = 30; // Not allowed, throws an error in strict modedelete obj.name; // Not allowed, throws an error in strict modeconsole.log(obj); // { name: 'Jane' } (age was not added, name was not deleted)
The object-integrity constraint ladder
Object.seal() is the middle of three increasingly restrictive integrity levels.
The arrows represent stronger guarantees, not a requirement to call each method in sequence.
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
Object.seal(obj);
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, so they cannot be deleted or have most descriptor attributes changed. One permitted transition remains: a data property with
writable: truecan be changed towritable: false. - Modifiable values: You can still change the values of existing properties as long as they are writable.
Example
// 'use strict'const person = {name: 'Alice',age: 25,};Object.seal(person);person.name = 'Bob'; // Allowedperson.age = 30; // Allowedperson.gender = 'female'; // Not allowed, throws an error in strict modedelete person.name; // Not allowed, throws an error in strict modeconsole.log(person); // { name: 'Bob', age: 30 } (gender not added, name not deleted)
Use cases
- Data integrity: Ensuring that an object structure remains unchanged, which can be useful in scenarios where the object represents a fixed schema.
- Shared contracts: Catching accidental additions or deletions when several modules share a fixed-shape object. It does not stop changes to writable values or nested objects and is not a security boundary.
Checking if an object is sealed
You can check if an object is sealed using the Object.isSealed() method.
const obj = { name: 'John' };Object.seal(obj);console.log(Object.isSealed(obj)); // true
Further reading
- MDN Web Docs on Object.seal()
- MDN Web Docs on Object.isSealed()
- JavaScript.info on property flags and descriptors