Object.freeze()
Object.freeze()
Section titled “Object.freeze()”Introduction
Section titled “Introduction”Object.freeze() makes an object immutable — you cannot add, delete, or change its properties. It’s a shallow freeze.
Example
Section titled “Example”const config = Object.freeze({ apiUrl: 'https://api.example.com', timeout: 5000});
config.apiUrl = 'https://evil.com'; // ❌ Fails silently (strict mode: throws)config.newProp = 'test'; // ❌ Cannot adddelete config.timeout; // ❌ Cannot deleteObject.isFrozen(config); // trueShallow Freeze
Section titled “Shallow Freeze”const config = Object.freeze({ settings: { theme: 'dark' }});
config.settings.theme = 'light'; // ✅ Allowed — nested object is not frozenDeep Freeze
Section titled “Deep Freeze”function deepFreeze(obj) { Object.keys(obj).forEach(key => { if (typeof obj[key] === 'object' && obj[key] !== null) { deepFreeze(obj[key]); } }); return Object.freeze(obj);}Summary
Section titled “Summary”Object.freeze()makes objects immutable (shallow)- Use for configuration objects and constants
- Deep freeze required for nested objects
- Check with
Object.isFrozen()