How to Seal Object in JavaScript: Syntax and Examples
To seal an object in JavaScript, use
Object.seal(object). This method prevents adding or removing properties but allows modifying existing ones.Syntax
The syntax to seal an object is simple:
Object.seal(obj): Seals the objectobj.- After sealing, you cannot add or delete properties.
- You can still change the values of existing properties.
javascript
Object.seal(obj);Example
This example shows sealing an object and what changes are allowed or blocked:
javascript
const car = { brand: 'Toyota', year: 2020 }; Object.seal(car); car.year = 2021; // Allowed: modifying existing property car.color = 'red'; // Ignored: cannot add new property delete car.brand; // Fails: cannot delete property console.log(car);
Output
{"brand":"Toyota","year":2021}
Common Pitfalls
Common mistakes when sealing objects include:
- Expecting sealing to make properties read-only (it does not).
- Trying to add or delete properties after sealing (these operations fail silently or throw errors in strict mode).
- Confusing
Object.seal()withObject.freeze(), which also prevents modifying existing properties.
javascript
const obj = { a: 1 }; Object.seal(obj); // Wrong: expecting this to fail obj.a = 2; // This works because sealing allows modification // Right: adding new property fails obj.b = 3; // Does not add property // Right: deleting property fails delete obj.a; // Does not delete property console.log(obj);
Output
{"a":2}
Quick Reference
| Method | Effect |
|---|---|
| Object.seal(obj) | Prevents adding/removing properties, allows modifying existing ones |
| Object.freeze(obj) | Prevents adding/removing/modifying properties |
| Object.preventExtensions(obj) | Prevents adding new properties only |
Key Takeaways
Use Object.seal(obj) to prevent adding or deleting properties on an object.
Sealed objects still allow changing values of existing properties.
Sealing is different from freezing; freezing also blocks changes to property values.
Adding or deleting properties after sealing fails silently or throws errors in strict mode.
Use Object.freeze() if you want to make an object completely immutable.