Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Object.freeze only works one level deep in JavaScript

38 Object.freeze stops at the first level

fair

Freeze a config object, try to write, add and delete a property, then try to change something nested inside it. Write deepFreeze for the case the built-in does not cover.

Stuck? Three hints, smallest first
  1. 1. These panels run in strict mode, so a write to a frozen object throws rather than failing quietly.
  2. 2. Object.freeze freezes the object’s own properties. A property whose value is an object is a reference, and the object it points at is untouched.
  3. 3. A recursive freeze walks the values and freezes each object it finds.

The answer

const attempt = (fn) => {
  try { return fn(); } catch (e) { return e.constructor.name; }
};

const config = Object.freeze({ branch: 'Ikeja', limits: { daily: 50000 } });

const written = attempt(() => { config.branch = 'Yaba'; return 'no throw'; });
const added = attempt(() => { config.extra = true; return 'no throw'; });
const removed = attempt(() => { delete config.branch; return 'no throw'; });

config.limits.daily = 1;                          // nothing stops this

const frozenList = Object.freeze([1, 2]);
const pushed = attempt(() => frozenList.push(3));

const deepFreeze = (o) => {
  for (const value of Object.values(o)) {
    if (value && typeof value === 'object') deepFreeze(value);
  }
  return Object.freeze(o);
};
const locked = deepFreeze({ branch: 'Yaba', limits: { daily: 5 } });
const deepWrite = attempt(() => { locked.limits.daily = 6; return 'no throw'; });

let holder = Object.freeze({ x: 1 });
holder = { x: 2 };                                // the variable was never frozen

console.log('write  :', written, '| add:', added, '| delete:', removed);
console.log('nested :', config.limits.daily, '<- changed');
console.log('frozen?:', Object.isFrozen(config), Object.isFrozen(config.limits));
console.log('array  :', pushed);
console.log('deep   :', deepWrite);
console.log('rebound:', holder);

Output


      
8 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 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('writing to a frozen property throws in strict mode', written, 'TypeError');
test('so does adding a new one', added, 'TypeError');
test('and deleting an existing one', removed, 'TypeError');
test('but a nested object is not frozen at all', config.limits.daily, 1);
test('and isFrozen says so plainly', [Object.isFrozen(config), Object.isFrozen(config.limits)], [true, false]);
test('freezing an array blocks push', pushed, 'TypeError');
test('a recursive freeze reaches the nesting', deepWrite, 'TypeError');
test('freeze locks the object, never the variable holding it', holder, { x: 2 });

Two independent misreadings of freeze are covered here. It is shallow, so freeze(config) protects nothing below the first level — the assertion that config.limits.daily is now 1 is the proof. And it acts on the object, not the binding: const stops the variable being pointed elsewhere, freeze stops the object being edited, and you need both to get what people usually mean by "constant".

In sloppy mode every one of those TypeErrors would instead be a silent no-op, which is far worse: the write looks like it worked and the value never changed. That is one of the strongest practical arguments for strict mode, and it is why these panels run in it.

Newsletter

New writing, when it lands.

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