Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Object.freeze in strict mode in JavaScript

80 A frozen tariff, and the write that throws in strict mode

fair

Freeze a tariff object and try four things on it: change a field, delete a field, add a field, and change something one level deeper. Then freeze an array and try to push. Note which of those throw and which quietly succeed, and say what const protects that freeze does not.

Stuck? Three hints, smallest first
  1. 1. In strict mode a write to a frozen property is a TypeError. In sloppy mode the same line does nothing at all.
  2. 2. Freezing is one level deep: the reference is locked, the object it points at is not.
  3. 3. const locks the binding; freeze locks the contents. They protect different things and neither implies the other.

The answer

const tariff = Object.freeze({
  base: 25000,
  perKm: 1500,
  areas: { Lekki: 2500, Ikeja: 1000 },
  zones: ['A', 'B'],
});

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

const changed = attempt(() => {
  tariff.base = 1;
});
const removed = attempt(() => {
  delete tariff.perKm;
});
const added = attempt(() => {
  tariff.surge = 2;
});
const nested = attempt(() => {
  tariff.areas.Lekki = 9999;
});
const pushedInside = attempt(() => {
  tariff.zones.push('C');
});

const stillOriginal = [tariff.base, tariff.perKm, 'surge' in tariff];
const nestedMoved = [tariff.areas.Lekki, tariff.zones];

const frozenList = Object.freeze(['garri', 'rice']);
const pushed = attempt(() => {
  frozenList.push('beans');
});
const sortedInPlace = attempt(() => {
  frozenList.sort();
});

const flags = Object.seal({ open: true, staff: 2 });
const sealedWrite = attempt(() => {
  flags.staff = 3;
});
const sealedAdd = attempt(() => {
  flags.closingTime = '18:00';
});
const states = [Object.isFrozen(tariff), Object.isSealed(tariff), Object.isFrozen(flags), Object.isSealed(flags)];

let rebindable = tariff;
rebindable = { base: 0 };
const primitivesPassThrough = [Object.freeze(5), Object.isFrozen(5)];

console.log('writes :', changed, removed, added, '| nested:', nested, pushedInside);
console.log('after  :', stillOriginal, nestedMoved);
console.log('array  :', pushed, sortedInPlace, '| sealed:', sealedWrite, sealedAdd);
console.log('states :', states, '| rebound:', rebindable.base);

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('changing, deleting and adding a property all throw on a frozen object', [changed, removed, added], ['TypeError', 'TypeError', 'TypeError']);
test('so the top level really is unchanged', stillOriginal, [25000, 1500, false]);
test('but one level down nothing is protected', [nested, pushedInside], ['allowed', 'allowed']);
test('and those changes stuck', nestedMoved, [9999, ['A', 'B', 'C']]);
test('a frozen array refuses push, and refuses to sort itself in place', [pushed, sortedInPlace], ['TypeError', 'TypeError']);
test('sealing allows writes to what exists but no new keys', [sealedWrite, sealedAdd, flags.staff], ['allowed', 'TypeError', 3]);
test('every frozen object is sealed; the reverse does not hold', states, [true, true, false, true]);
test('freeze locks the contents, not the name, so a let holding it can be rebound', rebindable.base, 0);
test('and freezing a primitive is a no-op that reports as already frozen', primitivesPassThrough, [5, true]);

Strict mode is what makes Object.freeze useful. Under it, every one of the three top-level attempts above raises a TypeError you can see in a stack trace; without it the assignment evaluates to the value you assigned, changes nothing, and reports nothing — a frozen object that lies about being writable. Everything in this course runs strict, which is why attempt can report an error name at all.

The shallowness is the part that bites. freeze makes each own property non-writable and non-configurable, and that is where it stops: tariff.areas cannot be repointed, but the object it points at is entirely open, and an array field can still be pushed to and sorted. A config object frozen at the top and mutated three levels down is a very common way to be surprised. Recursing over the properties is the fix, with the usual caveats about cycles and about not freezing things you did not create.

Keep const and freeze separate in your head. const says this name will never point at anything else; freeze says this object will never change. Object.seal sits between them: existing properties stay writable, no new ones may appear, and none may be deleted.

Newsletter

New writing, when it lands.

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