Object.freeze vs Object.seal in JavaScript
JavaScript provides built-in methods to control the mutability of
objects, with Object.freeze() and
Object.seal() being the two primary approaches for locking
down object structures. While both methods prevent properties from being
added or deleted, the core difference lies in how they handle property
values: Object.seal() allows you to modify the values of
existing properties, whereas Object.freeze() makes all
existing properties completely immutable and read-only.
Understanding Object.seal()
The Object.seal() method takes an object and prevents
new properties from being added to it, while also marking all existing
properties as non-configurable.
When an object is sealed: * Cannot add properties:
New properties cannot be added. * Cannot delete
properties: Existing properties cannot be deleted using the
delete operator. * Cannot reconfigure
properties: Property descriptors cannot be changed (for
example, converting a data property into an accessor property). *
Can modify values: You can still change the values of
existing writable properties.
const user = { name: "Alice", role: "Admin" };
Object.seal(user);
user.role = "User"; // Works: existing values can be updated
user.age = 30; // Fails: new properties cannot be added
delete user.name; // Fails: properties cannot be deletedUnderstanding Object.freeze()
The Object.freeze() method provides the highest level of
integrity for a JavaScript object. It performs everything that
Object.seal() does, with the additional step of making all
data properties non-writable.
When an object is frozen: * Cannot add properties: New properties cannot be added. * Cannot delete properties: Existing properties cannot be removed. * Cannot reconfigure properties: Descriptors cannot be modified. * Cannot modify values: Existing property values cannot be altered.
const config = { apiEndpoint: "https://api.example.com", timeout: 5000 };
Object.freeze(config);
config.timeout = 10000; // Fails: existing values cannot be changed
config.retries = 3; // Fails: new properties cannot be added
delete config.timeout; // Fails: properties cannot be deletedKey Differences at a Glance
| Action | Normal Object | Sealed Object
(Object.seal) |
Frozen Object
(Object.freeze) |
|---|---|---|---|
| Add New Properties | Allowed | Prevented | Prevented |
| Delete Existing Properties | Allowed | Prevented | Prevented |
| Modify Existing Values | Allowed | Allowed | Prevented |
| Reconfigure Descriptors | Allowed | Prevented | Prevented |
To check the state of an object, JavaScript provides corresponding
checking methods: Object.isSealed(obj) and
Object.isFrozen(obj).
Shallow Mutation Behavior
Both Object.freeze() and Object.seal()
perform shallow operations. If a sealed or frozen object contains nested
objects or arrays, those nested structures remain fully mutable unless
they are also explicitly sealed or frozen recursively.