HomeJAVASCRIPTWhat is the difference between Object.freeze and Object.seal?

What is the difference between Object.freeze and Object.seal?

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

FeatureObject.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 levelSemi-immutableFully immutable (shallow)

👉 In simple words:

  • Use seal when you want to keep the object structure fixed but still allow value changes.
  • Use freeze when you want the object to be completely immutable.

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *