javascript / intermediate
Snippet
Controlling Object Mutability with Object.seal()
Object.seal() prevents new properties from being added and existing properties from being removed, but allows modification of existing property values. This is ideal for fixed configuration objects where values may change but the structure must remain intact.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
const userConfig = {theme: 'dark',version: 1.0};Object.seal(userConfig);userConfig.theme = 'light'; // AlloweduserConfig.newSetting = true; // Fails (silent or TypeError in strict mode)delete userConfig.version; // Fails
Breakdown
1
Object.seal(userConfig);
Locks the structure of the object, preventing additions or deletions.
2
userConfig.theme = 'light';
Modifying existing properties is still permitted.
3
delete userConfig.version;
This operation will fail because sealed objects do not allow property removal.