Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Recursive deep freeze for nested objects in JavaScript

74 Object.freeze is one level deep

hard

Freeze an object with a nested object inside it and write to the nested one. Then write deepFreeze properly: it must handle a cycle, arrays, symbol keys, and it must not run any getter while walking. Finish by finding the one write a freeze cannot stop.

Stuck? Three hints, smallest first
  1. 1. Recurse over Reflect.ownKeys, not Object.keys, or symbol-keyed values stay writable.
  2. 2. A WeakSet of what you have already seen is what stops a cycle recursing for ever.
  3. 3. Read Object.getOwnPropertyDescriptor(obj, key).value. Reading obj[key] invokes accessors.

The answer

const attemptName = (fn) => { try { fn(); return 'no error'; } catch (err) { return err.name; } };

const shallow = Object.freeze({ till: 'Balogun 3', limits: { daily: 2000000 } });
const topRefused = attemptName(() => { shallow.till = 'Ikeja 1'; });
const nestedAllowed = attemptName(() => { shallow.limits.daily = 0; });
const nestedNow = shallow.limits.daily;
const frozenFlags = [Object.isFrozen(shallow), Object.isFrozen(shallow.limits)];

const deepFreeze = (value, seen = new WeakSet()) => {
  if (value === null || (typeof value !== 'object' && typeof value !== 'function')) return value;
  if (seen.has(value)) return value;                       // a cycle, already handled
  seen.add(value);
  for (const key of Reflect.ownKeys(value)) {              // symbol keys included
    const desc = Object.getOwnPropertyDescriptor(value, key);
    if (desc && 'value' in desc) deepFreeze(desc.value, seen);   // never runs a getter
  }
  return Object.freeze(value);
};

const AUDIT = Symbol('audit');
const config = {
  till: 'Balogun 3',
  limits: { daily: 2000000, perOrder: { naira: 500000 } },
  stops: ['Yaba', 'Ikeja'],
  [AUDIT]: { by: 'Adaeze' },
};
deepFreeze(config);

const deepRefused = [
  attemptName(() => { config.limits.daily = 0; }),
  attemptName(() => { config.limits.perOrder.naira = 0; }),
  attemptName(() => { config.stops.push('Ojota'); }),
  attemptName(() => { config[AUDIT].by = 'someone else'; }),
];
const frozenAllTheWay = [
  Object.isFrozen(config.limits.perOrder),
  Object.isFrozen(config.stops),
  Object.isFrozen(config[AUDIT]),
];
const dataIntact = [config.limits.perOrder.naira, config.stops.slice()];

const cyclic = { stop: 'Oshodi' };
cyclic.self = cyclic;
deepFreeze(cyclic);
const cycleHandled = [Object.isFrozen(cyclic), Object.isFrozen(cyclic.self), cyclic.self.self.stop];

let getterCalls = 0;
const lazy = { fare: 400, get total() { getterCalls++; return this.fare + 50; } };
deepFreeze(lazy);
const notCalledDuringFreeze = getterCalls;
const stillComputes = [lazy.total, getterCalls];

const till = (() => {
  let naira = 0;
  return { get naira() { return naira; }, set take(amount) { naira += amount; } };
})();
deepFreeze(till);
const setterRan = attemptName(() => { till.take = 45000; });
const stateMoved = till.naira;

console.log('shallow freeze  :', topRefused, nestedAllowed, '-> nested is now', nestedNow);
console.log('deep freeze     :', deepRefused);
console.log('cycle           :', cycleHandled);
console.log('setter          :', setterRan, '-> naira is now', stateMoved);

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('a plain freeze refuses the top level', [topRefused, frozenFlags[0]], ['TypeError', true]);
test('and lets a nested write straight through: freeze is one level deep', [nestedAllowed, nestedNow, frozenFlags[1]], ['no error', 0, false]);
test('deepFreeze refuses at every depth, arrays and symbol keys included', deepRefused, ['TypeError', 'TypeError', 'TypeError', 'TypeError']);
test('every nested object really is frozen, not just guarded', frozenAllTheWay, [true, true, true]);
test('and the data came through the walk unchanged', dataIntact, [500000, ['Yaba', 'Ikeja']]);
test('a cycle is handled by the seen set rather than recursing for ever', cycleHandled, [true, true, 'Oshodi']);
test('no getter ran during the freeze, because the walk reads descriptors', notCalledDuringFreeze, 0);
test('though the getter still computes afterwards', stillComputes, [450, 1]);
test('and freezing cannot stop a setter: it still moves state in its closure', [setterRan, stateMoved], ['no error', 45000]);

Object.freeze freezes one object. The second assertion is the whole problem: the top-level write threw and shallow.limits.daily = 0 succeeded, because limits is a different object and freezing the parent said nothing about it. Every "immutable config" bug looks like this.

Three details separate a working deepFreeze from the four-line version people write first. Reflect.ownKeys rather than Object.keys, or symbol-keyed values are missed entirely — and non-enumerable ones too. A WeakSet of visited objects, or a cycle recurses until the stack ends; WeakSet rather than Set so the bookkeeping does not pin the objects in memory. And reading getOwnPropertyDescriptor(obj, key).value rather than obj[key], so the walk does not invoke every accessor it passes — the seventh assertion. A getter can be expensive, can throw, can log, can lazily build the very object you are about to freeze; a function that "just freezes things" should not trigger any of that.

The last assertion is the limit of the whole idea. Freezing sets writable: false on data properties, but an accessor has no writable — it has a setter, and freezing only marks it non-configurable. Assigning to till.take still calls the setter, which still mutates the closed-over variable. A frozen object with accessors is not immutable, it is merely fixed in shape. Real immutability comes from not exposing the mutator.

Also worth knowing: freezing does not stop a proxy target from being replaced elsewhere, does not affect a Map's or Set's contents — the entries live in an internal slot, not in properties, as exercise 63 explains — and cannot be undone. There is no unfreeze.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.