1. Object.seal()
- What it does:
- Prevents adding new properties.
- Prevents deleting existing properties.
- You can still modify existing property values (if they are writable).
- Makes all properties non-configurable (can’t be deleted or redefined).
✅ Example:
const obj = { name: "Himanshu", age: 27 };
Object.seal(obj);
obj.age = 28; // ✅ Allowed (modifying value)
obj.city = "Delhi"; // ❌ Not allowed (adding new property)
delete obj.name; // ❌ Not allowed (deleting property)
console.log(obj); // { name: "Himanshu", age: 28 }
2. Object.freeze()
- What it does:
- Prevents adding new properties.
- Prevents deleting properties.
- Prevents modifying existing property values.
- Makes all properties non-writable and non-configurable.
- In short: The object becomes completely immutable (shallow freeze).
✅ Example:
const obj = { name: "Himanshu", age: 27 };
Object.freeze(obj);
obj.age = 28; // ❌ Not allowed (modifying value)
obj.city = "Delhi"; // ❌ Not allowed (adding new property)
delete obj.name; // ❌ Not allowed (deleting property)
console.log(obj); // { name: "Himanshu", age: 27 }
Key Difference Table
| Feature | Object.seal() | Object.freeze() |
|---|---|---|
| Add new properties | ❌ Not allowed | ❌ Not allowed |
| Delete properties | ❌ Not allowed | ❌ Not allowed |
| Modify property values | ✅ Allowed (if writable) | ❌ Not allowed |
| Change property config | ❌ Not allowed | ❌ Not allowed |
| Immutability level | Semi-immutable | Fully immutable (shallow) |
👉 In simple words:
- Use
sealwhen you want to keep the object structure fixed but still allow value changes. - Use
freezewhen you want the object to be completely immutable.
