Sub topic 14
Locking Objects: preventExtensions, seal, and freeze
JavaScript objects are open by default. Any code holding a reference can add properties, change values, and delete keys. Sometimes you want to stop that: configuration that must not drift, constants shared across modules, or state that only one function should ever modify. JavaScript gives you three built-in levels of restriction: Object.preventExtensions, Object.seal, and Object.freeze.
This chapter assumes you know the property attributes writable, enumerable, and configurable from the previous chapter on descriptors. It also assumes you know how the prototype chain resolves lookups and how shallow copies share nested objects. Each locking function is a shortcut that flips the object's extensibility flag and rewrites those attributes in bulk, so the descriptor model explains almost everything here.
Three Levels of Restriction
Each level includes everything the level below it does:
| Operation | Add new | Delete existing | Change values | Reconfigure attributes | Check with |
|---|---|---|---|---|---|
| `Object.preventExtensions` | No | Yes | Yes | Yes | `Object.isExtensible` (returns `false`) |
| `Object.seal` | No | No | Yes | No | `Object.isSealed` |
| `Object.freeze` | No | No | No (data properties) | No | `Object.isFrozen` |
All three return the same object you passed in, not a copy. That lets you write const x = Object.freeze({ ... }) in a single expression.
None of them can be undone. Once an object is non-extensible, no API makes it extensible again. If you need a modifiable version later, copy it.
Strict Mode Decides Whether Failures Are Loud
A forbidden write behaves differently depending on the mode:
- In sloppy mode, the default for classic scripts and CommonJS files without a directive, the write is silently ignored.
- In strict mode, which is on in ES modules, in class bodies, and in files starting with
"use strict", the write throws aTypeError.
Silent failure causes most of the real bugs with locked objects. Code appears to run fine while an assignment quietly does nothing. The examples below use "use strict" so the failures are visible, unless a note says otherwise.
preventExtensions: No New Properties
Object.preventExtensions clears the object's internal extensible flag. Existing properties are untouched. You can still change and delete them.
"use strict";
const point = { x: 1, y: 2 };
Object.preventExtensions(point);
point.x = 10; // allowed
delete point.y; // allowed
try {
point.z = 3;
} catch (e) {
console.log(e.constructor.name); // "TypeError"
}
console.log(point); // { x: 10 }
console.log(Object.isExtensible(point)); // falseA non-extensible object also cannot have its prototype changed. Object.setPrototypeOf(point, {}) throws a TypeError. This rule protects the object's shape from both directions, so lookups can't suddenly find new inherited properties either.
Use preventExtensions when typos are the danger. A property name typed wrong, such as user.emial = ..., creates a new property in an open object. In a non-extensible object under strict mode, it throws instead.
seal: Fixed Shape, Mutable Values
Object.seal calls preventExtensions and then sets configurable: false on every own property. Properties can't be deleted, and data properties can't be converted to accessors or the other way round. Writable values can still change.
"use strict";
const user = Object.seal({ name: "Lin", role: "admin" });
user.name = "Ana"; // allowed: still writable
try {
delete user.role;
} catch (e) {
console.log(e.constructor.name); // "TypeError"
}
console.log(Object.getOwnPropertyDescriptor(user, "name"));
// { value: "Ana", writable: true, enumerable: true, configurable: false }
console.log(Object.isSealed(user)); // trueA sealed object works like a record with a fixed set of fields. It fits state objects whose shape you define once and whose values change over time.
One detail of configurable: false: you can still change writable from true to false with Object.defineProperty, but not back. A sealed property can be narrowed further and never widened.
freeze: Read-Only Data Properties
Object.freeze seals the object and also sets writable: false on every own data property. This is the strongest built-in level.
"use strict";
const config = Object.freeze({ port: 8080, mode: "prod" });
try {
config.port = 9000;
} catch (e) {
console.log(e.constructor.name); // "TypeError"
}
console.log(config.port); // 8080
console.log(Object.isFrozen(config)); // trueAccessors Still Run
Freeze only changes writable on data properties. Accessor properties have no writable attribute, so their getters and setters keep working. A setter on a frozen object can still change state stored somewhere else:
"use strict";
const store = { n: 0 };
const counter = Object.freeze({
get value() { return store.n; },
set value(v) { store.n = v; }
});
counter.value = 5; // the setter runs, no error
console.log(counter.value); // 5
console.log(Object.isFrozen(counter)); // trueA frozen object guarantees that its own property slots won't change. It does not guarantee that reading a property always returns the same value.
freeze Is Shallow
Every locking function acts only on the object's own properties. A nested object is a separate object, reached through a reference that is now read-only. The nested object itself is not locked.
"use strict";
const settings = Object.freeze({ db: { host: "localhost" } });
settings.db.host = "example.com"; // allowed
console.log(settings.db.host); // "example.com"
console.log(Object.isFrozen(settings.db)); // falseTo lock a whole tree you have to recurse. The version below reads values through descriptors so it never runs getters, follows symbol keys through Reflect.ownKeys, and uses a WeakSet so circular references don't loop forever:
function deepFreeze(obj, seen = new WeakSet()) {
const isObject =
obj !== null && (typeof obj === "object" || typeof obj === "function");
if (!isObject || seen.has(obj)) return obj;
seen.add(obj);
for (const key of Reflect.ownKeys(obj)) {
const desc = Object.getOwnPropertyDescriptor(obj, key);
if ("value" in desc) deepFreeze(desc.value, seen);
}
return Object.freeze(obj);
}
const app = deepFreeze({ db: { host: "localhost" }, tags: ["a"] });
app.db.host = "x"; // ignored in sloppy mode, TypeError in strict mode
console.log(app.db.host); // "localhost"
console.log(Object.isFrozen(app.tags)); // trueGotchas
const Is Not freeze
const locks the binding: the variable can't be reassigned to point at another object. The object it points to stays fully mutable. Object.freeze locks the object and does nothing to the variable. They solve different problems and are often used together.
const a = { n: 1 };
a.n = 2; // fine: the object is mutable
// a = {}; // TypeError: assignment to constant variable
let b = Object.freeze({ n: 1 });
b = { n: 99 }; // fine: the binding is mutable
console.log(b.n); // 99Arrays Throw Even in Sloppy Mode
Built-in methods such as push, pop, splice, and sort are specified to throw when a write fails, whatever mode the calling code runs in. Plain index assignment follows the caller's mode. Run this without a strict directive:
const list = Object.freeze([1, 2]);
list[0] = 99; // sloppy mode: silently ignored
console.log(list); // [1, 2]
try {
list.push(3);
} catch (e) {
console.log(e.constructor.name); // "TypeError"
}Maps, Sets, and Internal State
Object.freeze locks properties. A Map keeps its entries in internal slots that are not properties, so freezing it changes nothing about set or delete:
const m = Object.freeze(new Map());
m.set("a", 1);
console.log(m.get("a")); // 1The same applies to Set, Date (its time value is internal, so setFullYear still works), and class instances with #private fields. To get a read-only collection, wrap it in an object that exposes only reading methods, or keep the collection private and hand out copies.
Frozen Prototypes Block Shadowing
Assigning a property normally creates an own property that shadows an inherited one. There is one exception: if the inherited property is a non-writable data property, plain assignment fails. Freezing a prototype therefore stops every object that inherits from it from overriding methods by assignment:
"use strict";
const base = Object.freeze({ greet() { return "hi"; } });
const child = Object.create(base);
try {
child.greet = () => "hello";
} catch (e) {
console.log(e.constructor.name); // "TypeError"
}
Object.defineProperty(child, "greet", {
value: () => "hello",
writable: true,
enumerable: true,
configurable: true
});
console.log(child.greet()); // "hello"Object.defineProperty defines the property directly on child without going through the assignment rules, so it works. Projects that freeze built-in prototypes for security, a technique called "hardening", run into this often.
isFrozen on Empty Objects
The is* checks test the current state, not the history of how the object got there. A non-extensible object with no properties counts as both sealed and frozen, because no property breaks either rule:
const empty = Object.preventExtensions({});
console.log(Object.isSealed(empty)); // true
console.log(Object.isFrozen(empty)); // trueChoosing a Level
| Situation | Choice |
|---|---|
| Catch typos that create new keys; values and keys may still change | `preventExtensions` |
| Fixed set of fields with changing values | `seal` |
| Constants, shared configuration, enum-like lookup tables | `freeze` |
| A whole nested structure must stay unchanged | `deepFreeze` or an immutable data library |
| Read-only view of a `Map`/`Set` | A wrapper object, not `freeze` |
Freezing has no meaningful runtime cost in modern engines. The real costs are silent failures in sloppy mode and false confidence about nested data. Run your code in strict mode, and remember that each call locks exactly one object.
Exercise
You run const s = Object.seal({ a: 1 }); in strict mode and then run s.a = 2; s.b = 3;. What happens on each line, and what is s afterward?
Show answer
s.a = 2 succeeds because sealed properties stay writable. s.b = 3 throws a TypeError because a sealed object is non-extensible. Afterward s is { a: 2 }.
Exercise
A module exports export const LIMITS = Object.freeze({ max: 10, ranges: [1, 5] });. Another module runs LIMITS.ranges.push(20). Does it succeed? Name two ways to prevent it.
Show answer
It succeeds. Freeze is shallow, so the ranges array is still extensible. To prevent it, freeze the array too (ranges: Object.freeze([1, 5])), or apply a recursive deepFreeze to LIMITS.
Exercise
Why can a setter on a frozen object still change what its getter returns?
Show answer
Freeze sets writable: false only on data properties. Accessor properties have no writable attribute, so their get and set functions keep running. If the setter stores state outside the frozen object, for example in a closure or another object, the getter can return new values.