What is Object.freeze and Object.seal in JavaScript
· Category: JavaScript
Short answer
Object.freeze prevents all changes to an object, while Object.seal allows modifying existing property values but prevents adding or removing properties.
Key differences
| Behavior | freeze | seal |
|---|---|---|
| Add properties | No | No |
| Delete properties | No | No |
| Modify values | No | Yes |
| Reconfigure descriptors | No | No |
Steps
- Freeze an object completely:
javascript const config = Object.freeze({ apiUrl: "https://api.example.com" }); config.apiUrl = "evil.com"; // silently fails in non-strict mode - Seal an object to preserve its shape:
javascript const user = Object.seal({ name: "Tom", age: 25 }); user.age = 26; // OK user.role = "admin"; // fails - Check state:
javascript Object.isFrozen(obj); Object.isSealed(obj); Object.isExtensible(obj);
Tips
- Both are shallow; nested objects remain mutable unless recursively frozen.
- Use
freezefor constants and configuration objects. Usesealwhen you want a fixed schema with mutable values.
Common issues
- Attempts to modify frozen objects throw in strict mode but fail silently otherwise.
- Freezing does not prevent reassignment of the variable binding itself.