Object.freeze() makes an object completely immutable — cannot add, delete or modify properties. Object.seal() allows changing values of existing properties, but prohibits adding new properties and deleting existing ones. Main difference: freeze locks everything, seal locks only structure.
Object.freeze() and Object.seal() are methods for protecting objects from changes. They are similar, but have important differences.
Makes object completely immutable:
const obj = { name: 'John', age: 25 };
Object.freeze(obj);
// All these operations won't work
obj.name = 'Peter'; // Won't change
obj.city = 'Moscow'; // Won't add
delete obj.age; // Won't deleteProtects only object structure:
const obj = { name: 'John', age: 25 };
Object.seal(obj);
// Can change values
obj.name = 'Peter'; // Will work
// Cannot add/delete properties
obj.city = 'Moscow'; // Won't add
delete obj.age; // Won't delete// Configuration that cannot be changed
const config = {
apiEndpoint: 'https://api.example.com',
timeout: 5000
};
Object.freeze(config);
// Now config is fully protected// Object with fixed set of fields
const user = { name: 'John', age: 25 };
Object.seal(user);
// Can update user data
user.name = 'Peter';
user.age = 30;
// But cannot add new fields
user.email = 'test@example.com'; // Won't workconst obj = { name: 'John' };
Object.freeze(obj);
console.log(Object.isFrozen(obj)); // trueconst obj = { name: 'John' };
Object.seal(obj);
console.log(Object.isSealed(obj)); // trueconst obj = {
user: { name: 'John' }
};
Object.freeze(obj);
obj.user.name = 'Peter'; // Will work! Nested object not frozenconst obj = { name: 'John' };
Object.freeze(obj);
// No way to "unfreeze" object// ❌ No error in non-strict mode
const obj = { name: 'John' };
Object.freeze(obj);
obj.name = 'Peter'; // Silently won't work
// ✅ In strict mode will be error
'use strict';
obj.name = 'Peter'; // TypeError// ❌ Think everything is frozen
const obj = { user: { name: 'John' } };
Object.freeze(obj);
obj.user.name = 'Peter'; // Will work!
// ✅ Need to freeze nested objects
Object.freeze(obj.user);
obj.user.name = 'Peter'; // Now won't workUnderstanding difference between freeze and seal helps create more reliable code and prevent unwanted data changes.
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪