Seal, Freeze, PreventExtensions ( ) Methods - Object Extensibility
JavaScript has three methods that lock an object, each stricter than the one before. Object.preventExtensions() stops new properties being added, Object.seal() also stops properties being deleted or reconfigured, and Object.freeze() also stops their values changing. Each works on the object you pass in, returns that same object, and cannot be undone. They are useful for configuration and constant tables that nothing should change by accident.
What each one allows
Section titled “What each one allows”| After calling | preventExtensions |
seal |
freeze |
|---|---|---|---|
| Add a property | no | no | no |
| Change a property’s value | yes | yes | no |
| Delete a property | yes | no | no |
| Change a property’s settings | yes | no | no |
| Change the prototype | no | no | no |
seal works by making every property non-configurable, and freeze also makes every data property read-only, using the settings described in Property Descriptors. A sealed property that is writable can still be made read-only, because that one change is allowed on a non-configurable property.
The same table, tested in code. The file starts with 'use strict', so each refused change throws an error that can be caught:
'use strict';
function attempt(label, action) { try { action(); console.log(`${label}: allowed`); } catch (err) { console.log(`${label}: ${err.constructor.name}`); }}
function tryEverything(name, lock) { const settings = { theme: 'dark', fontSize: 14 }; lock(settings); console.log(`-- ${name}`); attempt('add', () => { settings.language = 'en-GB'; }); attempt('change', () => { settings.fontSize = 16; }); attempt('delete', () => { delete settings.theme; }); attempt('reconfigure', () => Object.defineProperty(settings, 'fontSize', { enumerable: false })); attempt('new prototype', () => Object.setPrototypeOf(settings, {}));}
tryEverything('preventExtensions', Object.preventExtensions);tryEverything('seal', Object.seal);tryEverything('freeze', Object.freeze);This prints:
-- preventExtensionsadd: TypeErrorchange: alloweddelete: allowedreconfigure: allowednew prototype: TypeError-- sealadd: TypeErrorchange: alloweddelete: TypeErrorreconfigure: TypeErrornew prototype: TypeError-- freezeadd: TypeErrorchange: TypeErrordelete: TypeErrorreconfigure: TypeErrornew prototype: TypeErrorSilent failure in sloppy mode
Section titled “Silent failure in sloppy mode”Without strict mode, assigning to a frozen property or adding a property to a locked object does nothing and raises no error, which can hide a bug for a long time:
const settings = { theme: 'dark' };Object.freeze(settings);
settings.theme = 'light';settings.language = 'en-GB';console.log(settings);This prints:
{ theme: 'dark' }This example runs as a classic script, and browsers’ classic scripts behave the same way. ES modules and class bodies are always strict, so there the same assignments throw a TypeError. Object.defineProperty and Object.setPrototypeOf throw in either mode.
Checking an object
Section titled “Checking an object”Object.isExtensible(), Object.isSealed() and Object.isFrozen() report an object’s state:
const settings = Object.seal({ theme: 'dark' });
console.log(Object.isExtensible(settings));console.log(Object.isSealed(settings));console.log(Object.isFrozen(settings));console.log(Object.isFrozen(Object.preventExtensions({})));This prints:
falsetruefalsetrueThe checks look at the properties as they are, not at which method was called. An empty object that cannot be extended has no properties left to change, so it counts as sealed and frozen too.
Freezing is shallow
Section titled “Freezing is shallow”freeze locks the object’s own properties, but an object or array stored in one of them is a separate object, and it stays open:
'use strict';
const config = Object.freeze({ name: 'reports', recipients: ['ana@example.com'],});
config.recipients.push('ben@example.com');console.log(config.recipients);
function deepFreeze(value) { for (const key of Reflect.ownKeys(value)) { const child = value[key]; if (child !== null && typeof child === 'object') { deepFreeze(child); } } return Object.freeze(value);}
const locked = deepFreeze({ name: 'reports', recipients: ['ana@example.com'] });try { locked.recipients.push('ben@example.com');} catch (err) { console.log(err.message);}This prints:
[ 'ana@example.com', 'ben@example.com' ]Cannot add property 1, object is not extensibleconfig.recipients cannot be pointed at a different array, but the array it holds can still be changed. deepFreeze walks through every nested object and freezes each one, which suits plain data. Do not use it on objects that share parts with other code, since it freezes those shared parts for everyone.
The prototype is not locked
Section titled “The prototype is not locked”None of the three methods touches the object’s prototype. Properties the object inherits can still change, and they show through:
'use strict';
const defaults = { currency: 'GBP' };const shop = Object.create(defaults);shop.name = 'Corner Shop';Object.freeze(shop);
defaults.currency = 'EUR';defaults.vatRate = 0.2;console.log(shop.currency, shop.vatRate);This prints:
EUR 0.2shop itself cannot be changed and cannot be given a different prototype, but the defaults object it inherits from is still open. Prototypes explains how inherited properties are looked up.
Steve Griffith covers this topic in his video Object seal, freeze, and preventExtensions.