Object.freeze()
is a method that prevents modifications to an object. Once an object is frozen.
✅ You cannot add new properties.
✅ You cannot modify existing properties.
✅ You cannot delete properties.
const user = {
name: "Alice",
age: 25
};
Object.freeze(user);
user.age = 30; // ❌ Won't change
user.city = "New York"; // ❌ Won't add
delete user.name; // ❌ Won't delete
console.log(user);
// output: { name: "Alice", age: 25 }
👉 It only works on the first level. It does not freeze nested objects.
Object.seal()
is a method that prevents adding or deleting properties from an object but allows modification of existing properties.
const user = {
name: "Alice",
age: 25
};
Object.seal(user);
user.age = 30; // ✅ Allowed (modification works)
user.city = "New York"; // ❌ Not allowed (new property won't be added)
delete user.name; // ❌ Not allowed (deletion won't work)
console.log(user);
// output: { name: "Alice", age: 30 }
📌 Summary:
Feature Object.seal() | Object.freeze()
Modify properties = ✅ Yes ❌ No
Add new properties = ❌ No ❌ No
Delete properties = ❌ No ❌ No