Object.freeze seal And preventExtensions Compared
Object.preventExtensions blocks new keys, seal also blocks deletions, freeze also blocks writes; sealed objects still accept value changes in place.
Code
// three gradations: preventExtensions only blocks new keys; seal also blocks deletions; freeze also blocks value writes
const ext = Object.preventExtensions({ a: 1 });
try {
ext.b = 2; // throws TypeError in strict mode, silently fails otherwise
} catch {
// adding a key is blocked
}
console.log('preventExtensions keys:', Object.keys(ext).join(','));
const sealed = Object.seal({ a: 1 });
sealed.a = 9; // seal still allows value writes: the in-place change succeeds
console.log('sealed write ok:', sealed.a === 9);
try {
delete sealed.a; // the deletion is blocked
} catch {
// the deletion is blocked
}
console.log('sealed keys intact:', Object.keys(sealed).join(','), 'isSealed:', Object.isSealed(sealed));
const frozen = Object.freeze({ a: 1 });
try {
frozen.a = 9; // the value write is blocked
} catch {
// the write is blocked
}
console.log('frozen value kept:', frozen.a === 1, 'isFrozen:', Object.isFrozen(frozen));
console.log('still extensible :', Object.isExtensible(frozen), Object.isExtensible(sealed), Object.isExtensible(ext));What the code does
Top-level bindings ext, sealed, frozen hold the demo state — nothing sits inside a function scope.
Applying it
The demo output is labeled (preventExtensions keys:, sealed write ok:, sealed keys intact:), so every printed line maps back to its originating operation.
Statements that matter
sealed.a = 9; // seal still allows value writes: the in-place change succeeds
console.log('sealed write ok:', sealed.a === 9);
ext.b = 2; // throws TypeError in strict mode, silently fails otherwise
} catch {
// adding a key is blocked
}
const ext = Object.preventExtensions({ a: 1 });
Interactive Tools for This Topic
FAQ
- Which packages does this snippet need?
- None. Every symbol the code uses resolves inside the standard library. Its state lives in module-level bindings: `ext`, `sealed`, `frozen`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.