Have you ever accidentally modified an object in JavaScript and wished you could prevent unwanted changes? JavaScript provides two powerful methods—Object.seal() and Object.freeze()—to control how objects can be modified. In this article, we’ll explore their differences, use cases, and when to use each.
Real Life Analogy-
Imagine you have a diary. You decide that no new pages can be added, but you can still edit what's written—that’s like Object.seal(). But if you decide that nothing in the diary can be changed at all, that’s like Object.freeze()!
What is Object.seal()?
Object.seal() method prevents adding or removing properties but allows modifying existing properties. What is Object.freeze()?
Object.freeze() method makes an object completely immutable—you cannot add, modify, or delete properties.Real-World Use Cases
When to Use Object.seal()?
- When you want to allow modifications but prevent structural changes.
- Example: Sealing a configuration object so properties remain unchanged, but values can be updated.
When to Use Object.freeze()?
- When you want to completely lock an object’s state.
- Example: Freezing constants to ensure they never change.
Object.seal() vs Object.freeze()
| Feature | Object.seal() | Object.freeze() |
|---|---|---|
| Modify existing properties | ✅ Yes | ❌ No |
| Add new properties | ❌ No | ❌ No |
| Delete properties | ❌ No | ❌ No |
| Completely immutable | ❌ No | ✅ Yes |
Conclusion
In summary, Object.seal() and Object.freeze() help control object modifications in JavaScript.
- Use
Object.seal()when you need to prevent adding/removing properties but allow modifications. - Use
Object.freeze()when you need full immutability.