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

AddDeleteChange valuesReconfigure
Object.preventExtensionsNoYesYesYes
Object.sealNoNoYesNo
Object.freezeNoNoNoNo

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 of darkMode), 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";
2
3const settings = Object.seal({ theme: "light", fontSize: 14, darkMode: false });
4
5settings.fontSize = 16; // allowed: changing an existing value
6settings.darkMode = true; // allowed
7console.log(settings); // { theme: "light", fontSize: 16, darkMode: true }
8
9for (const attempt of [
10 () => (settings.darkmode = true), // typo would silently create a property without seal
11 () => 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}
20
21console.log(Object.isSealed(settings), Object.isFrozen(settings)); // true false
22
23// Comparison with preventExtensions and freeze
24const ext = Object.preventExtensions({ a: 1 });
25delete ext.a; // allowed with preventExtensions
26console.log("a" in ext, Object.isExtensible(ext)); // false false
27
28const 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: TypeError
33}

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.

Open in study app