Freeze vs Seal in JavaScript: Key Differences and Usage
Object.freeze() makes an object fully immutable by preventing adding, deleting, or changing properties. Object.seal() allows existing properties to be changed but stops adding or deleting properties.Quick Comparison
Here is a quick table comparing freeze and seal methods in JavaScript:
| Feature | Object.freeze() | Object.seal() |
|---|---|---|
| Add new properties | No | No |
| Delete existing properties | No | No |
| Modify existing properties | No | Yes |
| Writable properties | No | Yes |
| Configurable properties | No | No |
| Shallow effect | Yes | Yes |
Key Differences
Object.freeze() locks an object completely. It prevents adding new properties, deleting existing ones, or changing any property values. Also, it makes all existing properties non-configurable and non-writable, so the object becomes fully immutable at the top level.
On the other hand, Object.seal() stops adding or deleting properties but still allows changing the values of existing properties if they are writable. It makes all existing properties non-configurable but does not affect writability, so you can update values but cannot remove or add properties.
Both methods only affect the object shallowly, meaning nested objects inside can still be changed unless they are also frozen or sealed separately.
Code Comparison
const obj = { name: 'Alice', age: 25 }; Object.freeze(obj); obj.name = 'Bob'; // Ignored in strict mode or fails silently obj.city = 'Paris'; // Ignored delete obj.age; // Ignored console.log(obj);
Object.seal() Equivalent
const obj = { name: 'Alice', age: 25 }; Object.seal(obj); obj.name = 'Bob'; // Allowed obj.city = 'Paris'; // Ignored delete obj.age; // Ignored console.log(obj);
When to Use Which
Choose Object.freeze() when you want to make sure an object cannot be changed in any way, ensuring full immutability at the top level. This is useful for constants or fixed configuration objects.
Choose Object.seal() when you want to prevent adding or removing properties but still allow updating existing property values. This is helpful when you want to lock the shape of an object but keep its data mutable.
Key Takeaways
Object.freeze() makes an object fully immutable by blocking all changes.Object.seal() prevents adding or deleting properties but allows modifying existing ones.freeze for complete immutability and seal to lock object shape but keep values changeable.