Preventing Extensions, Sealing, and Freezing
You'll learn how to lock down JavaScript objects at three different levels of protection.
Sometimes you want to prevent an object from being modified—either partially or completely. JavaScript provides three methods to restrict what can be done to an object, each offering a different level of protection.
The Three Levels of Object Protection
Object.preventExtensions()
This is the mildest restriction. It prevents new properties from being added to an object, but you can still modify or delete existing properties.
const user = { name: 'Alice', age: 30 };
Object.preventExtensions(user);
user.age = 31; // ✓ Works (modifying existing property)
delete user.age; // ✓ Works (deleting existing property)
user.email = 'a@b.com'; // ✗ Fails silently (or throws in strict mode)
Object.seal()
This provides medium protection. A sealed object cannot have properties added or deleted, but you can still modify existing property values. Behind the scenes, it marks all properties as non-configurable.
const config = { theme: 'dark', lang: 'en' };
Object.seal(config);
config.theme = 'light'; // ✓ Works (modifying existing property)
config.font = 'Arial'; // ✗ Fails (cannot add)
delete config.lang; // ✗ Fails (cannot delete)
Object.freeze()
This is the strictest protection. A frozen object is completely immutable—you cannot add, delete, or modify properties. It's like turning your object to ice.
const constants = { PI: 3.14159, E: 2.71828 };
Object.freeze(constants);
constants.PI = 3.14; // ✗ Fails (cannot modify)
constants.G = 9.81; // ✗ Fails (cannot add)
delete constants.E; // ✗ Fails (cannot delete)
Think of it like document permissions: preventExtensions is "no new pages," seal is "locked table of contents," and freeze is "read-only mode."
Key Takeaway: Use Object.preventExtensions() to stop growth, Object.seal() to lock structure, and Object.freeze() to make objects completely immutable.