JavaScriptMedium
What is the purpose of Object.seal()?
Object.seal(obj) locks an object's shape: no properties can be added or removed and existing ones cannot be reconfigured, but the values of existing writable properties can still be changed.
Freeze vs seal vs preventExtensions
| Add | Delete | Change values | Reconfigure | |
|---|---|---|---|---|
Object.preventExtensions | No | Yes | Yes | Yes |
Object.seal | No | No | Yes | No |
Object.freeze | No | No | No | No |
Check with Object.isExtensible, Object.isSealed, Object.isFrozen. Like freeze, seal is shallow and returns the same object; in strict mode forbidden operations throw a TypeError.
When seal is useful
- Fixed-shape objects whose values change but whose keys must not: a settings object, a form model, a state record. Sealing catches typos like
settings.darkmode = true(instead ofdarkMode), which would otherwise silently create a new property. - Protecting an object passed to plugins so they can update known fields but not add or remove fields.
- Engines like objects with stable shapes; sealing documents that intent (though the performance effect is usually negligible).
In TypeScript
Static types already prevent unknown properties at compile time; Object.seal adds the same guarantee at runtime, which matters for data coming from plain JavaScript or untyped boundaries.
Code example
js
1"use strict";23const settings = Object.seal({ theme: "light", fontSize: 14, darkMode: false });45settings.fontSize = 16; // allowed: changing an existing value6settings.darkMode = true; // allowed7console.log(settings); // { theme: "light", fontSize: 16, darkMode: true }89for (const attempt of [10 () => (settings.darkmode = true), // typo would silently create a property without seal11 () => delete settings.theme,12 () => Object.defineProperty(settings, "theme", { enumerable: false }),13]) {14 try {15 attempt();16 } catch (e) {17 console.log(e.name); // TypeError (x3)18 }19}2021console.log(Object.isSealed(settings), Object.isFrozen(settings)); // true false2223// Comparison with preventExtensions and freeze24const ext = Object.preventExtensions({ a: 1 });25delete ext.a; // allowed with preventExtensions26console.log("a" in ext, Object.isExtensible(ext)); // false false2728const frozen = Object.freeze({ a: 1 });29try {30 frozen.a = 2;31} catch (e) {32 console.log("freeze blocks value changes:", e.name); // freeze blocks value changes: TypeError33}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.