Sub topic 8
Enforcing Immutability with Object.freeze
The earlier chapters relied on discipline. You copied with spread, used map and filter, and promised yourself never to write state.user.name = .... Promises break, though, especially in a large codebase with many contributors. Object.freeze lets the JavaScript engine enforce the rule for you. This chapter covers what freezing actually does, where it stops working, and how to use it well.
This chapter assumes you know how to write functions and recursion in JavaScript and how strict mode differs from sloppy mode. It also assumes you have read the earlier chapters on reference semantics, const, and shallow copies.
What Object.freeze Does
Every object property has attributes. A data property has writable (can the value change?) and configurable (can the property be deleted or redefined?). The object as a whole is extensible when new properties can be added to it.
Object.freeze(obj) does three things:
- Marks the object as non-extensible, so you cannot add properties.
- Sets every own property to
configurable: false, so you cannot delete or redefine properties. - Sets every own data property to
writable: false, so you cannot reassign values.
It returns the same object, not a copy. That detail matters: Object.freeze changes the object in place, so every reference to it sees the frozen version.
'use strict';
const point = { x: 1, y: 2 };
const same = Object.freeze(point);
console.log(same === point); // true, freeze returns the same object
console.log(Object.isFrozen(point)); // true
console.log(Object.getOwnPropertyDescriptor(point, 'x'));
// { value: 1, writable: false, enumerable: true, configurable: false }
try {
point.x = 10;
} catch (err) {
console.log(err instanceof TypeError); // true
}
try {
delete point.y;
} catch (err) {
console.log(err.message); // Cannot delete property 'y' of #<Object>
}
try {
point.z = 3;
} catch (err) {
console.log(err.message); // Cannot add property z, object is not extensible
}Error message wording differs between engines. The messages above come from V8, which Node.js and Chrome use.
Strict Mode Versus Sloppy Mode
Strict mode changes what happens when a write is rejected. In strict mode, a rejected write throws a TypeError. In sloppy mode, the engine ignores the write silently and your code keeps running with the old value.
// Run this file without 'use strict' and as a CommonJS script, not a module.
const settings = Object.freeze({ theme: 'dark' });
settings.theme = 'light'; // silently ignored
console.log(settings.theme); // 'dark'The silent failure is the more dangerous of the two. The bug moves from the line that tried the write to some later line that expected the new value.
The Freeze Family: preventExtensions, seal, freeze
JavaScript has three levels of lockdown, and each one includes the one before it.
| Operation | Add properties | Delete properties | Reassign values | Check with |
|---|---|---|---|---|
| `Object.preventExtensions` | No | Yes | Yes | `Object.isExtensible` |
| `Object.seal` | No | No | Yes | `Object.isSealed` |
| `Object.freeze` | No | No | No | `Object.isFrozen` |
None of these operations can be undone. No Object.unfreeze exists. To get a changeable version, you make a copy, and a spread copy of a frozen object is an ordinary, unfrozen object.
Freezing Is Shallow
Object.freeze only affects the object's own properties. If a property holds a reference to another object, the reference cannot change, but the object it points to is still fully mutable. This is the same shallow behavior you saw with spread copies.
'use strict';
const config = Object.freeze({
api: { retries: 3 },
hosts: ['a.example.com']
});
config.api.retries = 5; // allowed: config.api is not frozen
config.hosts.push('b.example.com'); // allowed: the array is not frozen
console.log(config.api.retries); // 5
console.log(config.hosts.length); // 2
try {
config.api = {}; // rejected: the reference itself is frozen
} catch (err) {
console.log(err instanceof TypeError); // true
}Shallow freezing is enough for flat records, such as a set of enum-like constants. For nested state you need to freeze recursively.
Writing a Deep Freeze
A first deep freeze walks the property values and freezes every object it finds:
'use strict';
function deepFreezeNaive(obj) {
for (const value of Object.values(obj)) {
if (value !== null && typeof value === 'object') {
deepFreezeNaive(value);
}
}
return Object.freeze(obj);
}
const config = deepFreezeNaive({ api: { retries: 3 } });
console.log(Object.isFrozen(config.api)); // trueThis works for plain trees, but it has three gaps:
- Circular references. If
a.self = a, the function recurses forever and throwsRangeError: Maximum call stack size exceeded, because it freezes each object only after visiting its children. - Hidden keys.
Object.valuesskips symbol keys and non-enumerable properties, so objects stored under those keys stay mutable. - Functions. A function is an object with its own properties, but
typeof fn === 'function', so the check above skips it.
A sturdier version tracks visited objects in a WeakSet and uses Reflect.ownKeys, which returns every own key:
'use strict';
function deepFreeze(root) {
const seen = new WeakSet();
function visit(obj) {
if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) {
return;
}
if (seen.has(obj)) {
return;
}
seen.add(obj);
for (const key of Reflect.ownKeys(obj)) {
const descriptor = Object.getOwnPropertyDescriptor(obj, key);
// Only follow data properties; reading a getter could run arbitrary code.
if (descriptor && 'value' in descriptor) {
visit(descriptor.value);
}
}
Object.freeze(obj);
}
visit(root);
return root;
}
const secret = Symbol('secret');
const node = { name: 'root', [secret]: { token: 'abc' } };
node.self = node; // circular reference
deepFreeze(node);
console.log(Object.isFrozen(node)); // true
console.log(Object.isFrozen(node[secret])); // true
console.log(node.self === node); // true, no infinite loopWhere Freezing Stops Working
Even a correct deep freeze has limits. Some of them surprise experienced developers.
Internal slots: Map, Set, and Date
Map, Set, and Date keep their data in internal slots, not in properties. Freezing locks the properties, so the methods that change the internal data keep working.
'use strict';
const cache = Object.freeze(new Map([['a', 1]]));
cache.set('b', 2); // works
console.log(cache.size); // 2
const when = Object.freeze(new Date(0));
when.setFullYear(2030); // works
console.log(when.getFullYear()); // 2030To keep these values immutable, wrap them behind a read-only interface, convert them to plain objects or arrays, or rely on the copy-on-update rules from earlier chapters.
Typed arrays
You cannot freeze a typed array that has elements. The engine throws, because the elements live in an ArrayBuffer that other views could share.
'use strict';
try {
Object.freeze(new Uint8Array(4));
} catch (err) {
console.log(err instanceof TypeError); // true: cannot freeze array buffer views with elements
}
console.log(Object.isFrozen(Object.freeze(new Uint8Array(0)))); // true, empty is allowedA deep freeze that walks into a structure holding a typed array will throw. If your data can contain binary buffers, skip ArrayBuffer.isView(value) values explicitly.
Accessors and prototypes
Freezing makes accessor properties non-configurable, but it does not stop a setter from running. If the setter writes to a closure variable or another object, that state still changes. Freezing also leaves the prototype alone. Object.freeze(instance) does not freeze Class.prototype, so someone can still add or replace methods that every instance inherits.
Frozen does not mean deeply equal or safe to share across threads
Freezing gives you no new copy and no structural comparison. Two frozen objects with the same contents are still different references. Freezing also does not stop structuredClone or postMessage from copying the data, and the copy is not frozen.
When and How to Freeze in Practice
Freezing helps most when it is used as a tripwire during development. A common pattern freezes state only in development builds, so accidental mutations throw immediately in tests and local runs:
'use strict';
const isDev = process.env.NODE_ENV !== 'production';
function createStore(initial) {
let state = isDev ? deepFreeze(initial) : initial;
return {
getState: () => state,
setState(next) {
state = isDev ? deepFreeze(next) : next;
}
};
}
function deepFreeze(obj) {
for (const value of Object.values(obj)) {
if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) {
deepFreeze(value);
}
}
return Object.freeze(obj);
}
const store = createStore({ todos: [{ id: 1, done: false }] });
try {
store.getState().todos[0].done = true;
} catch (err) {
console.log('Caught mutation:', err.message);
}
const prev = store.getState();
store.setState({ ...prev, todos: prev.todos.map(t => ({ ...t, done: true })) });
console.log(store.getState().todos[0].done); // trueThe !Object.isFrozen(value) check in this store is a deliberate shortcut. With immutable updates, unchanged branches are reused from the previous state and are already deep-frozen, so skipping them keeps each setState cost proportional to what changed. The tip above still applies to code that receives objects from outside: there, use the WeakSet version.
Common errors to watch for:
| Mistake | Symptom | Fix |
|---|---|---|
| Expecting `freeze` to return a copy | Original is frozen too, later code that owns it breaks | Copy first, then freeze the copy |
| Freezing only the top level | Nested writes succeed silently | Use a recursive deep freeze |
| Running writers in sloppy mode | Writes vanish without an error | Use modules or `'use strict'` |
| Freezing `Map`, `Set`, or `Date` | `set`, `add`, or `setX` still change data | Convert, wrap, or copy instead |
| Deep freezing large state on every update in production | Measurable slowdowns | Freeze only in development, or skip already-frozen branches |
Exercises
Exercise
In a CommonJS file without 'use strict', you run const o = Object.freeze({ list: [1] }); o.list.push(2); o.list = []; console.log(o.list);. What is printed, and why?
Show answer
It prints [1, 2]. The push succeeds because freeze is shallow and the array itself is not frozen. The reassignment o.list = [] is rejected because the property is non-writable, and in sloppy mode that rejection is silent, so no error is thrown.
Exercise
Why does the naive deepFreeze, which freezes after recursing into Object.values, crash on const a = {}; a.self = a; deepFreezeNaive(a);, and what change prevents it?
Show answer
It visits a, then a.self (which is a again), and repeats forever because a is never marked as visited before its children are processed. The stack overflows with a RangeError. Tracking visited objects in a WeakSet and returning early on a repeat visit prevents this.
Exercise
A colleague deep-freezes an object holding { sessions: new Set(['x']) } and says sessions can no longer change. Are they right?
Show answer
No. Freezing locks properties, but a Set stores its entries in an internal slot. state.sessions.add('y') still works after freezing. To protect it, convert it to a frozen array, hide it behind a read-only API, or replace it with a new Set on each update.
Exercise
Object.freeze(obj) returns a value. Is Object.freeze(obj) === obj true or false, and what does that imply for code that still holds the old reference?
Show answer
It is true. freeze changes the object in place and returns the same reference, so every other part of the program holding obj now sees a frozen object. If any of that code was mutating obj, it will start throwing in strict mode or silently fail in sloppy mode.