JavaScript gives you ways to prevent accidental changes to your objects. One powerful method is Object.freeze(). It locks down an object, making it completely immutable at the top level.
What Does Object.freeze() Do?
Object.freeze() prevents:
- Adding new properties
- Removing existing properties
- Changing existing property values
- Changing property descriptors (like writable or configurable)
const settings = {
theme: 'dark',
layout: 'grid'
};
Object.freeze(settings);
settings.theme = 'light'; // Won't change
settings.newProp = 'test'; // Won't be added
delete settings.layout; // Won't be deleted
console.log(settings.theme); // 'dark'
Is It Really Frozen?
You can test if an object is frozen using:
Object.isFrozen(settings); // true
Shallow Freeze Warning
Object.freeze() only affects the object at the top level. If the object contains nested objects or arrays, those are still mutable:
const config = {
options: {
debug: true
}
};
Object.freeze(config);
config.options.debug = false; // This will work!
console.log(config.options.debug); // false
To fully freeze nested structures, you’ll need a deep freeze function.
How to Deep Freeze an Object
Here’s a simple recursive deep freeze:
function deepFreeze(obj) {
Object.getOwnPropertyNames(obj).forEach(function(prop) {
if (typeof obj[prop] === 'object' && obj[prop] !== null) {
deepFreeze(obj[prop]);
}
});
return Object.freeze(obj);
}
const deepSettings = {
theme: 'light',
nested: {
mode: 'auto'
}
};
deepFreeze(deepSettings);
deepSettings.nested.mode = 'manual'; // Won’t work now
When Should You Use Object.freeze()?
- To protect configuration or constant objects
- To avoid accidental mutations in shared objects
- To write safer, more predictable code
Browser Support
Object.freeze() is well-supported across all modern browsers (including IE9+).
Conclusion
Object.freeze() is a handy tool when you want to lock down an object and prevent unwanted changes. It’s especially useful in large apps where shared objects should not be accidentally modified. Just remember — it only freezes the top level. For full protection, use a deep freeze strategy.
By freezing objects, you make your code more robust, intentional, and easier to debug.
Post a Comment