Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Write a deepFreeze function in JavaScript

126 deepFreeze, and everything a shallow freeze misses

fair

Show that Object.freeze protects one level only, by mutating a nested value inside a frozen object. Then write deepFreeze that recurses, prove a nested write and an array push both throw, and find the two things it still cannot protect: a Map's contents, and its own behaviour on a cyclic object.

Stuck? Three hints, smallest first
  1. 1. Recurse over Object.values(value), and stop at anything that is not an object.
  2. 2. Freeze the object before recursing into it, and bail out early on something already frozen — that is what keeps a cycle from looping for ever.
  3. 3. A Map keeps its entries in internal slots, not in properties, so there is nothing there for freeze to reach.

The answer

const deepFreeze = (value) => {
  if (value === null || typeof value !== 'object' || Object.isFrozen(value)) return value;
  Object.freeze(value);
  Object.values(value).forEach((inner) => deepFreeze(inner));
  return value;
};

const shallow = Object.freeze({ shop: 'Balogun Stores', tariffs: { lekki: 250000 } });
let shallowTop = 'no error';
try { shallow.shop = 'somewhere else'; } catch (e) { shallowTop = e.constructor.name; }
shallow.tariffs.lekki = 1;
const leaked = shallow.tariffs.lekki;

const deep = deepFreeze({ shop: 'Balogun Stores', tariffs: { lekki: 250000 }, zones: ['Yaba'] });
let deepNested = 'no error';
try { deep.tariffs.lekki = 1; } catch (e) { deepNested = e.constructor.name; }
let pushed = 'no error';
try { deep.zones.push('Ikeja'); } catch (e) { pushed = e.constructor.name; }

const withMap = deepFreeze({ seen: new Map([['Yaba', 1]]) });
withMap.seen.set('Ketu', 2);

const knot = { name: 'knot' };
knot.self = knot;
deepFreeze(knot);

console.log('shallow :', shallowTop, '| nested value is now', leaked);
console.log('deep    :', deepNested, pushed, '| tariff still', deep.tariffs.lekki);
console.log('map     :', [...withMap.seen], '| cycle frozen:', Object.isFrozen(knot));

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('freezing stops a write to the object itself', shallowTop, 'TypeError');
test('but the object one level down was never frozen, so this succeeded', leaked, 1);
test('deepFreeze reaches it, and the write throws under strict mode', deepNested, 'TypeError');
test('a push into a frozen array throws too, since it cannot be extended', pushed, 'TypeError');
test('frozen all the way down', [Object.isFrozen(deep), Object.isFrozen(deep.tariffs), Object.isFrozen(deep.zones)], [true, true, true]);
test('and the values survived the attempts unchanged', [deep.tariffs.lekki, deep.zones], [250000, ['Yaba']]);
test('a Map keeps its entries out of reach of freeze, so it still grew', [...withMap.seen], [['Yaba', 1], ['Ketu', 2]]);
test('freezing before recursing is what lets a cycle terminate', [Object.isFrozen(knot), knot.self === knot], [true, true]);
test('primitives need no freezing: they already report as frozen', [deepFreeze(7), Object.isFrozen('Lagos')], [7, true]);

The one-line summary: Object.freeze is shallow, and almost every use of it in real code wants to be deep. A frozen configuration object whose nested tariff table can still be rewritten gives you the comfort of immutability with none of the guarantee, and the second assertion above is that mutation succeeding in silence.

Two details in the recursion matter. Freezing before descending, plus the isFrozen early return, is what makes a cyclic structure terminate — do it the other way round and knot.self recurses until the stack ends. And the recursion has to stop at non-objects, since Object.freeze on a primitive is a no-op that returns it unchanged.

What it cannot do is worth knowing before you rely on it. A Map, Set, Date or class instance with private fields keeps its state in internal slots, so freezing the wrapper leaves the contents wide open. Getters still run. And under sloppy mode all these failures are silent — it is "use strict" that turns them into the TypeErrors asserted here, which is the only reason you would ever find out.

Newsletter

New writing, when it lands.

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