0
0
JavascriptComparisonBeginner · 3 min read

Freeze vs Seal in JavaScript: Key Differences and Usage

In JavaScript, 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:

FeatureObject.freeze()Object.seal()
Add new propertiesNoNo
Delete existing propertiesNoNo
Modify existing propertiesNoYes
Writable propertiesNoYes
Configurable propertiesNoNo
Shallow effectYesYes
⚖️

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

javascript
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);
Output
{"name":"Alice","age":25}
↔️

Object.seal() Equivalent

javascript
const obj = { name: 'Alice', age: 25 };
Object.seal(obj);

obj.name = 'Bob'; // Allowed
obj.city = 'Paris'; // Ignored
delete obj.age; // Ignored

console.log(obj);
Output
{"name":"Bob","age":25}
🎯

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.
Both methods only affect the object shallowly, not nested objects.
Use freeze for complete immutability and seal to lock object shape but keep values changeable.