JavaScriptFundamental (ES6), part 2
preventExtensions vs seal vs freeze in JavaScript
73 preventExtensions, seal and freeze
fairThree levels of lock-down. Apply each to the same object and build the matrix: can you add a key, change one, delete one? Confirm it with isExtensible, isSealed and isFrozen, read the descriptors each one leaves behind, and try push on a frozen array.
Stuck? Three hints, smallest first
- 1. One blocks additions. The next also blocks deletions. The last also blocks writes.
- 2. Sealing sets
configurable: false; freezing also setswritable: falseon data properties. - 3. A frozen array has a non-writable
length, sopushcannot even grow it.
const attemptName = (fn) => { try { fn(); return 'no error'; } catch (err) { return err.name; } };
const tryAll = (obj) => [
attemptName(() => { obj.zone = 'Mainland'; }), // add
attemptName(() => { obj.fare = 500; }), // change
attemptName(() => { delete obj.till; }), // delete
];
const noAdding = Object.preventExtensions({ fare: 400, till: 'Balogun 3' });
const sealed = Object.seal({ fare: 400, till: 'Balogun 3' });
const frozen = Object.freeze({ fare: 400, till: 'Balogun 3' });
const preventResults = tryAll(noAdding);
const sealResults = tryAll(sealed);
const freezeResults = tryAll(frozen);
const whatSurvived = [noAdding.fare, sealed.fare, frozen.fare];
const flags = (obj) => [Object.isExtensible(obj), Object.isSealed(obj), Object.isFrozen(obj)];
const matrix = [flags(noAdding), flags(sealed), flags(frozen)];
const attrs = (obj) => {
const d = Object.getOwnPropertyDescriptor(obj, 'fare');
return [d.writable, d.configurable];
};
const descriptors = [attrs(noAdding), attrs(sealed), attrs(frozen)];
const frozenList = Object.freeze(['Yaba', 'Ikeja']);
const pushRefused = attemptName(() => frozenList.push('Ojota'));
const elementRefused = attemptName(() => { frozenList[0] = 'Ojota'; });
const listUnchanged = frozenList.slice();
const reflectSays = [
Reflect.set(frozen, 'fare', 500),
Reflect.deleteProperty(sealed, 'till'),
Reflect.defineProperty(noAdding, 'zone', { value: 'Mainland' }),
];
const emptyFrozenByDefault = [Object.isFrozen(Object.preventExtensions({})), Object.isFrozen(Object.preventExtensions({ a: 1 }))];
console.log('preventExtensions:', preventResults);
console.log('seal :', sealResults);
console.log('freeze :', freezeResults);
console.log('flags :', matrix);
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.
test('preventExtensions blocks additions only', preventResults, ['TypeError', 'no error', 'no error']);
test('seal blocks additions and deletions, and still allows writes', sealResults, ['TypeError', 'no error', 'TypeError']);
test('freeze blocks all three', freezeResults, ['TypeError', 'TypeError', 'TypeError']);
test('so the write landed on the first two and not on the third', whatSurvived, [500, 500, 400]);
test('the three predicates agree, and frozen implies sealed', matrix, [[false, false, false], [false, true, false], [false, true, true]]);
test('sealing only clears configurable; freezing clears writable as well', descriptors, [[true, true], [true, false], [false, false]]);
test('a frozen array refuses push and element writes alike', [pushRefused, elementRefused, listUnchanged], ['TypeError', 'TypeError', ['Yaba', 'Ikeja']]);
test('Reflect reports each refusal as false instead of throwing', reflectSays, [false, false, false]);
test('and an empty non-extensible object is already sealed and frozen', emptyFrozenByDefault, [true, false]);
Three concentric locks, each adding one prohibition. preventExtensions stops new keys. seal adds "no deletions" by clearing configurable. freeze adds "no writes" by clearing writable as well. The sixth assertion is the mechanism rather than the vocabulary: these are not three separate flags on the object, they are one extensibility bit plus what each function does to the existing descriptors.
The gap people fall into is between seal and freeze. A sealed object still accepts writes to every existing key — the second assertion — so sealing a configuration object protects its shape and nothing about its contents. That is sometimes exactly right: a fixed set of fields whose values change. It is never a substitute for immutability.
The frozen array is worth trying once. push does not fail because arrays are special-cased; it fails because length is now non-writable, and push has to write it. Same for pop, sort, reverse and splice — every mutating method on a frozen array throws in strict mode, and each one throws from inside a built-in, so the stack points at your line and not at the freeze.
The last assertion is a genuine quirk: isFrozen and isSealed ask "is there anything left that could change", so a non-extensible object with no properties is already both. And note Reflect.set, Reflect.deleteProperty and Reflect.defineProperty return false where the operators throw — the same pairing as exercise 64, and the way to test for a lock without a try.