π 1. Why Protect Objects?
- Prevent accidental changes
- Secure data from tampering
- Lock configuration/settings
- Improve code stability and debugging
β 2. Protection Levels in JavaScript
Method | Prevent Adding | Prevent Deleting | Prevent Changing | Prevent Reconfiguring |
---|---|---|---|---|
Object.preventExtensions() | β | β | β | β |
Object.seal() | β | β | β | β |
Object.freeze() | β | β | β | β |
π 3. Object.preventExtensions()
Prevents adding new properties, but existing ones can still be changed or deleted.
jsCopyEditconst user = { name: "Alice" };
Object.preventExtensions(user);
user.age = 30; // β Won't add
console.log(user.age); // undefined
user.name = "Bob"; // β
Allowed
delete user.name; // β
Allowed
π 4. Object.seal()
Prevents adding or deleting properties. Values can still be modified.
jsCopyEditconst user = { name: "Alice" };
Object.seal(user);
user.age = 30; // β Won't add
delete user.name; // β Won't delete
user.name = "Bob"; // β
Can update value
π§ 5. Object.freeze()
Makes the object completely immutable: can’t add, delete, or change properties.
jsCopyEditconst config = {
apiKey: "12345"
};
Object.freeze(config);
config.apiKey = "54321"; // β No change
config.url = "api.com"; // β Won't add
delete config.apiKey; // β Won't delete
π
Object.freeze()
is shallow: it only applies to the top-level properties. To deep-freeze, you must recursively freeze nested objects.
π 6. Checking Protection State
jsCopyEditObject.isExtensible(obj); // false if preventExtensions used
Object.isSealed(obj); // true if sealed
Object.isFrozen(obj); // true if frozen
π 7. Deep Freezing Utility Function
jsCopyEditfunction deepFreeze(obj) {
Object.getOwnPropertyNames(obj).forEach(name => {
const value = obj[name];
if (value && typeof value === "object") {
deepFreeze(value);
}
});
return Object.freeze(obj);
}
// Usage
const settings = {
server: {
host: "localhost",
port: 8080
}
};
deepFreeze(settings);
settings.server.port = 3000; // β Won't change
π§ͺ Practice Challenge
Create an object bankAccount
:
- With properties:
owner
,balance
- Use
Object.seal()
to prevent property removal or addition - Add a method
deposit(amount)
to increase balance
π‘ Summary Table
Function | Purpose |
---|---|
Object.preventExtensions() | Disallow adding properties |
Object.seal() | Disallow add/delete, allow update |
Object.freeze() | Full lock-down, immutable |
Object.isFrozen(obj) | Check freeze status |
deepFreeze(obj) | Recursively freeze an object |
Would you like:
- π§ͺ Interactive sandbox or playground?
- π Downloadable PDF version?
- β Quiz on object protection methods?