Sub topic 8
Enforcing Immutability with Object.freeze
This chapter assumes you know strict mode, the difference between primitives and references, and how spread makes shallow copies. Earlier chapters avoided mutation by agreement: you chose to copy rather than change. Object.freeze lets the JavaScript engine enforce that choice, so an accidental mutation is caught instead of passing silently.
What Object.freeze Does
Object.freeze(obj) changes the object in place and returns that same object. After the call:
- you cannot add new properties
- you cannot delete existing properties
- you cannot reassign existing data properties
- you cannot reconfigure property descriptors or change the prototype
Freezing does not make a copy. It locks the object you pass in.
'use strict';
const point = Object.freeze({ x: 1, y: 2, tags: ['origin'] });
try {
point.x = 10;
} catch (err) {
console.log(err instanceof TypeError); // true
}
point.tags.push('labelled'); // allowed: the nested array is not frozen
console.log(point.tags); // ['origin', 'labelled']
console.log(Object.isFrozen(point)); // true
console.log(Object.isFrozen(point.tags)); // falseStrict Mode Decides How Failures Look
A write to a frozen object always fails. Strict mode decides whether you hear about the failure.
ES modules and class bodies always run in strict mode. Older scripts without 'use strict' will ignore the write without any error, and that kind of bug is hard to track down.
freeze, seal, and preventExtensions
JavaScript has three levels of locking. Mixing them up is a common mistake.
| Method | Add properties | Delete properties | Reassign values |
|---|---|---|---|
| `Object.preventExtensions` | No | Yes | Yes |
| `Object.seal` | No | No | Yes |
| `Object.freeze` | No | No | No |
Freezing Deeply
Object.freeze is shallow, like spread. To lock a whole tree, walk it and freeze each object. The version below freezes an object before visiting its children. It also skips objects that are already frozen, so circular references do not cause infinite recursion.
'use strict';
function deepFreeze(obj) {
if (obj === null || typeof obj !== 'object' || Object.isFrozen(obj)) {
return obj;
}
Object.freeze(obj);
for (const value of Object.values(obj)) {
deepFreeze(value);
}
return obj;
}
const config = { api: { retries: 3, hosts: ['a.example'] } };
config.self = config; // circular reference
deepFreeze(config);
console.log(Object.isFrozen(config.api.hosts)); // true
try {
config.api.retries = 5;
} catch (err) {
console.log(err.message); // Cannot assign to read only property 'retries' ...
}Object.values only visits own enumerable string-keyed properties. If you need to cover symbol keys or non-enumerable properties too, use Reflect.ownKeys(obj).
Limits of Freezing
- Map and Set:
Object.freeze(new Map()).set('k', 1)still works, because entries are internal slots, not properties. - Date:
setFullYearstill changes a frozen Date. - Typed arrays:
Object.freeze(new Uint8Array(4))throws a TypeError, because typed arrays with elements cannot be frozen. - Already-frozen objects: the guard in
deepFreezeskips them, including any unfrozen children. A frozen object that holds a mutable child stays partly mutable. - Cost: deep freezing walks the whole tree on every call. On large state that updates often, this cost shows up in profiles.
A common pattern is to deep freeze state only in development and tests, where it catches mutation bugs early, and to skip it in production builds. Libraries such as Immer, covered in a later chapter, use this approach and freeze the results they produce.
Exercise
In an ES module, you run const s = Object.freeze({ list: [1] }); s.list.push(2); s.list = [];. What happens on each of the last two statements, and why?
Show answer
s.list.push(2) succeeds because freezing is shallow and the array itself is not frozen. s.list = [] throws a TypeError because list is a property of the frozen object and ES modules always run in strict mode.
Exercise
Why does the deepFreeze function call Object.freeze(obj) before looping over its values instead of after?
Show answer
When an object is frozen first, a circular reference that leads back to it hits the Object.isFrozen check and returns immediately. If the function froze the object after the loop, it would recurse forever on a cycle.