🟢 EasyObjects📖 Theory Question

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

💡

Hint

freeze = truly immutable; seal = no add/delete but values can change

Full Answer

Both prevent structural changes but differ in degree:

  • Object.freeze() — no add, no delete, no value change. Completely locked.
  • Object.seal() — no add, no delete, but existing values CAN be changed.
// freeze
const config = Object.freeze({ host: 'localhost', port: 3000 });
config.port = 9999;     // silently fails (TypeError in strict)
config.debug = true;    // silently fails
delete config.host;     // false
console.log(config.port); // 3000 — unchanged

// seal
const sealed = Object.seal({ x: 1, y: 2 });
sealed.x = 99;          // ✅ allowed — value change is OK
sealed.z = 3;           // ❌ silently fails — no new props
delete sealed.x;        // ❌ fails — no delete

// Critical gotcha: BOTH are SHALLOW
const frozen = Object.freeze({ nested: { a: 1 } });
frozen.nested.a = 99;   // ⚠️ WORKS — nested object is not frozen!

// Deep freeze (recursive)
function deepFreeze(obj) {
  Object.getOwnPropertyNames(obj).forEach(name => {
    if (typeof obj[name] === 'object' && obj[name] !== null) {
      deepFreeze(obj[name]);
    }
  });
  return Object.freeze(obj);
}
💡 Use freeze() for config constants and action type objects in Redux. Remember it's shallow — deep freeze recursively if needed.

More Objects Questions

🟢 EasyHow does prototypal inheritance work in JavaScript?🟢 EasyWhat is the difference between shallow copy and deep copy?🟡 MediumWhat are property descriptors and property flags (writable, enumerable, configurable)?🟢 EasyWhat are getters and setters in JavaScript?

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint