How to Use Object.seal in JavaScript: Syntax and Examples
Use
Object.seal(object) to prevent adding or deleting properties on an object, but still allow changing existing property values. It locks the object's structure but keeps properties writable.Syntax
The Object.seal() method takes one argument, the object you want to seal. It returns the same object but sealed.
object: The target object to seal.
After sealing, you cannot add or remove properties, but you can still change existing property values.
javascript
Object.seal(object)Example
This example shows how sealing an object prevents adding or deleting properties but allows modifying existing ones.
javascript
const user = { name: 'Alice', age: 25 }; Object.seal(user); user.age = 26; // Allowed: modifying existing property user.city = 'Paris'; // Ignored: cannot add new property delete user.name; // Ignored: cannot delete property console.log(user);
Output
{"name":"Alice","age":26}
Common Pitfalls
Common mistakes include expecting Object.seal() to make properties read-only or to prevent value changes. It only stops adding or removing properties, not modifying them.
Also, sealing is shallow: nested objects inside the sealed object can still be changed.
javascript
const obj = { a: 1, b: { c: 2 } }; Object.seal(obj); obj.a = 10; // Works: property value changed obj.b.c = 20; // Works: nested object is not sealed obj.d = 4; // Fails silently or throws in strict mode delete obj.a; // Fails silently or throws in strict mode console.log(obj);
Output
{"a":10,"b":{"c":20}}
Quick Reference
- Prevents: Adding or deleting properties.
- Allows: Modifying existing property values.
- Returns: The sealed object.
- Shallow: Only seals the object itself, not nested objects.
Key Takeaways
Object.seal() stops adding or deleting properties but allows changing existing ones.
Sealing is shallow; nested objects remain mutable.
Trying to add or delete properties after sealing fails silently or throws in strict mode.
Use Object.seal() to lock object structure while keeping property values editable.
It returns the same object, now sealed.