Lock an object’s property set
Protect a configuration object's shape after initialization while allowing selected writable values to update.
JS Puzzles · Const
Object.seal(obj) prevents adding or removing properties and makes existing properties non-configurable. Writable existing values can still change.
Object.seal makes an object non-extensible and marks every existing property as non-configurable. The object keeps its current properties, so additions and removals are blocked, but existing data-property values may still change when writable.
Object.seal(obj)| Name | Type | Description |
|---|---|---|
obj | object | The object to seal. |
The same object that was passed to the method.
const settings = { theme: "dark" };
Object.seal(settings);
settings.theme = "light";
console.log(settings.theme); // "light"
settings.language = "en"; // ignored in non-strict mode
console.log(Object.isSealed(settings)); // trueSealing keeps the existing property set fixed while still allowing writable property values to change.
Protect a configuration object's shape after initialization while allowing selected writable values to update.
Prevent consumers from deleting or adding public fields without making every value immutable.
Apply a shallow structural restriction before passing an object across a module boundary.
Object.seal prevents extensions and makes all existing properties non-configurable. Therefore, properties cannot be added or removed, but writable existing values can still be changed.
Follow-up: How does it differ from Object.freeze()? Object.freeze also makes existing data properties non-writable, whereas Object.seal leaves writable values mutable.
The method returns the same object reference that it receives; it does not create a sealed copy. The object itself becomes non-extensible and its existing properties become non-configurable.
Follow-up: How could you preserve the original object while sealing independently? Create a copy first, then pass that copy to Object.seal.
A sealed object is non-extensible and has no configurable own properties. Object.isSealed can be used to test that state, returning true when those conditions hold.
Follow-up: Is every non-extensible object sealed? No. Non-extensibility alone is insufficient; all existing properties must also be non-configurable.
Object.freeze()Object.preventExtensions()Object.isSealed()Object.isExtensible()property descriptors