⚡ Frozen on the Outside, Fully Mutable on the Inside
`Object.freeze()` looks like it locks an object down completely, and attempts to reassign its top-level properties do get silently ignored (or throw, in strict mode) – but freeze is shallow: any object or array nested inside the frozen object is a completely separate object reference, and freezing the parent does absolutely nothing to it.
🔎 The Problem
const config = Object.freeze({
name: "checkout-service",
limits: { maxRetries: 3, timeoutMs: 5000 },
});
config.name = "something-else"; // silently ignored - top-level, frozen
console.log(config.name); // "checkout-service" - unchanged, as expected
config.limits.maxRetries = 99; // NOT ignored - `limits` was never frozen
console.log(config.limits.maxRetries); // 99 - the "frozen" config just changed
✅ Fix: Freeze Every Level That Needs to Be Immutable
- Write a small recursive `deepFreeze()` helper that calls `Object.freeze()` on the object itself and then recurses into every property that’s an object or array – this is the only way `Object.freeze()` actually reaches nested structures, since it was never designed to do so on its own.
- For anything beyond a small config object, a library built for this (Immer, or the built-in `structuredClone()` combined with treating the clone as read-only by convention) scales much better than a hand-rolled deep freeze, especially for deeply nested or frequently-updated state.
- In TypeScript, `Readonly<T>` (or a recursive `DeepReadonly<T>` utility type) catches attempted nested mutations at compile time – which is a stronger guarantee than `Object.freeze()` alone provides, since freeze is a runtime-only, shallow protection.
⚠️ Why the Bug Hides Until State Actually Depends on It
- A `console.log` of the frozen object right after creation shows exactly what you expect, because nothing has mutated yet – the bug only becomes visible once some later code path reaches in and changes a nested value, often far away from where the object was originally frozen.
- This is a common source of confusing behavior in Redux-style state management, where reducers are expected to treat state as immutable – a shallow freeze gives a false sense of safety while a nested object is still silently mutated in place.
Object.freeze() protects exactly one layer – everything nested one level deeper is exactly as mutable as it would’ve been without freeze at all.
