Sub topic 14
Locking Objects: preventExtensions, seal, and freeze
This chapter assumes you already know property descriptors (writable, enumerable, configurable), the difference between a reference and a copy, and how strict mode changes error behavior. JavaScript has three built-in ways to restrict changes to an object. Each one is stricter than the one before it, and none of them can be undone.
Three Levels of Restriction
Each level includes everything the level below it does and adds one more rule.
| Operation | preventExtensions | seal | freeze |
|---|---|---|---|
| Add a property | Blocked | Blocked | Blocked |
| Delete a property | Allowed | Blocked | Blocked |
| Change a value | Allowed | Allowed | Blocked |
| Change attributes or convert to accessor | Allowed | Blocked | Blocked |
| Check with | `Object.isExtensible` | `Object.isSealed` | `Object.isFrozen` |
A blocked operation fails silently in sloppy mode. In strict mode it throws a TypeError. The examples below use strict mode so that the failures are visible.
preventExtensions: No New Properties
"use strict";
const settings = { theme: "dark", lang: "en" };
Object.preventExtensions(settings);
settings.theme = "light"; // allowed
delete settings.lang; // allowed
try {
settings.fontSize = 14;
} catch (e) {
console.log(e.name); // "TypeError"
}
console.log(settings); // { theme: "light" }
console.log(Object.isExtensible(settings)); // falseAfter this call, the object's prototype is locked as well. Object.setPrototypeOf(settings, {}) throws a TypeError. Properties inherited from the prototype can still change, because the prototype object itself is not locked.
seal: Fixed Shape, Changeable Values
Object.seal prevents extensions and sets configurable: false on every own property. The object's set of keys is now fixed, but writable values can still be changed.
"use strict";
const point = Object.seal({ x: 1, y: 2 });
point.x = 10; // allowed
try {
delete point.y;
} catch (e) {
console.log(e.name); // "TypeError"
}
console.log(Object.getOwnPropertyDescriptor(point, "x"));
// { value: 10, writable: true, enumerable: true, configurable: false }
console.log(Object.isSealed(point)); // trueUse seal when an object should keep a known shape, such as a record with a fixed set of fields, but its values still need to change.
freeze: Read-Only, but Only One Level Deep
Object.freeze seals the object and also sets writable: false on every data property. Two gaps remain:
- The freeze is shallow. Nested objects can still be changed. The earlier chapter's
config.db.hostexample showed this. - Accessors still run. A frozen object's setter can still be called, and it can change state stored outside the object.
To freeze a whole object graph, you have to walk it yourself:
"use strict";
function deepFreeze(obj) {
Object.freeze(obj);
for (const value of Object.values(obj)) {
if (value !== null && typeof value === "object" && !Object.isFrozen(value)) {
deepFreeze(value);
}
}
return obj;
}
const app = deepFreeze({ db: { host: "localhost", ports: [5432] } });
try {
app.db.ports.push(5433);
} catch (e) {
console.log(e.name); // "TypeError"
}
console.log(Object.isFrozen(app.db.ports)); // trueThe function freezes the current object before it recurses, so circular references end: an object that has already been visited is already frozen and gets skipped. Object.values lists only enumerable string-keyed properties. Use Reflect.ownKeys if the object also has symbol keys or non-enumerable properties.
Common Errors
- Expecting an error in sloppy mode. Writes to a frozen object fail silently there, so bugs hide. Use modules or
"use strict", both of which run in strict mode. - Assuming
constfreezes.conststops you from reassigning the variable. It does nothing to the object the variable refers to. - Freezing for performance. Freezing exists for correctness. Don't rely on it to speed up code.
Exercise
An object is created with const o = Object.seal({ a: 1 }). In strict mode, which of these succeed: o.a = 2, o.b = 3, delete o.a, Object.defineProperty(o, "a", { enumerable: false })?
Show answer
Only o.a = 2 succeeds. o.b = 3 throws because a sealed object cannot be extended. delete o.a throws because a is non-configurable. The defineProperty call throws because changing enumerable on a non-configurable property is not allowed.
Exercise
After const f = Object.freeze({ list: [] }), does f.list.push(1) work? Why or why not?
Show answer
Yes. Object.freeze is shallow. It makes the list property non-writable, so f.list cannot be reassigned, but the array it refers to is not frozen and can still be changed.