JavaScript Object Protection
14 April 2025 | Category: JavaScript
In JavaScript, objects are dynamic by default. You can add, modify, or delete properties at any time. However, in many cases—like building secure apps or APIs—you need to protect objects from unwanted changes.
JavaScript offers several built-in methods to control and restrict how objects behave. These include:
Object.preventExtensions()
Object.seal()
Object.freeze()
🔐 1. Object.preventExtensions()
This method prevents new properties from being added to an object. However, existing properties can still be modified or deleted.
🧪 Example:
const car = { brand: "Toyota" };
Object.preventExtensions(car);
car.model = "Corolla"; // ❌ Ignored in strict mode or silently fails
console.log(car.model); // undefined
car.brand = "Honda"; // ✅ Allowed
delete car.brand; // ✅ Allowed
✅ Use this when you want to lock the structure (but not values) of an object.
🔒 2. Object.seal()
This method seals an object:
- ❌ You can’t add or delete properties.
- ✅ You can modify existing properties.
🧪 Example:
const user = {
name: "Alice"
};
Object.seal(user);
user.age = 30; // ❌ Can't add
delete user.name; // ❌ Can't delete
user.name = "Bob"; // ✅ Can modify
console.log(user); // { name: "Bob" }
✅ Great for when you want to preserve the shape of an object but still allow updates.
🧊 3. Object.freeze()
This is the most strict method. It makes an object:
- ❌ Non-extensible (no new properties)
- ❌ Non-deletable
- ❌ Non-modifiable
It effectively makes the object read-only.
🧪 Example:
const config = {
apiKey: "12345"
};
Object.freeze(config);
config.apiKey = "54321"; // ❌ Ignored
delete config.apiKey; // ❌ Ignored
config.newKey = "test"; // ❌ Ignored
console.log(config.apiKey); // "12345"
✅ Use this for constant settings, configs, or final values.
📦 Bonus: Deep Freeze Function
By default, Object.freeze()
only works shallowly (top-level only). Here’s how you can deeply freeze an object:
function deepFreeze(obj) {
Object.getOwnPropertyNames(obj).forEach((prop) => {
if (typeof obj[prop] === 'object' && obj[prop] !== null) {
deepFreeze(obj[prop]);
}
});
return Object.freeze(obj);
}
const settings = {
theme: {
darkMode: true
}
};
deepFreeze(settings);
settings.theme.darkMode = false; // ❌ Won’t change
🛑 Checking Object Status
JavaScript provides built-in methods to check an object’s protection level:
Object.isExtensible(obj); // true/false
Object.isSealed(obj); // true/false
Object.isFrozen(obj); // true/false
✅ Summary Table
Method | Add Props | Delete Props | Modify Props |
---|---|---|---|
preventExtensions() | ❌ | ✅ | ✅ |
seal() | ❌ | ❌ | ✅ |
freeze() | ❌ | ❌ | ❌ |
🧠 Use Case Examples
preventExtensions
: Prevent API payloads from injecting extra dataseal
: Maintain structure of a form’s default valuesfreeze
: Secure app configurations or constants