protection
Object.freeze
Freezes an object: new properties cannot be added, existing properties cannot be removed, and their values, writability, and configurability cannot be changed. Returns the same object.
Object.freeze(obj) Parameters
| Parameter | Purpose |
|---|---|
| obj | The object to freeze |
| returns | The same (now frozen) object |
Examples
const o = Object.freeze({ a: 1 });
try { o.a = 2; } catch (e) {}
console.log(o.a); Logs 1 — assignment silently fails (throws in strict mode)
const o = Object.freeze({ nested: { count: 0 } });
o.nested.count = 99;
console.log(o.nested.count); Logs 99 — freeze is SHALLOW; nested objects remain mutable
console.log(Object.isFrozen(Object.freeze({}))); Logs true
const deepFreeze = obj => {
Object.values(obj).forEach(v => v && typeof v === 'object' && deepFreeze(v));
return Object.freeze(obj);
};
const o = deepFreeze({ n: { x: 1 } });
console.log(Object.isFrozen(o.n)); Logs true — recursive freeze for deep immutability
Gotcha
Object.freeze is SHALLOW — nested objects and arrays inside a frozen object remain fully mutable. Mutations silently fail in sloppy mode but throw a TypeError in strict mode.
Related methods
Object.isFrozen
Returns true if the object is frozen — non-extensible, and every own property is non-configurable and (if a data property) non-writable. Primitives are considered frozen.
Object.seal
Seals an object: prevents new properties from being added and marks all existing properties as non-configurable. Existing writable properties can still be reassigned.
Object.preventExtensions
Prevents new properties from being added to an object, but existing properties can still be modified, deleted, or reconfigured. The weakest of the three protection levels.
Object.isSealed
Returns true if the object is sealed — non-extensible and all own properties are non-configurable. Frozen objects are always sealed; primitives are considered sealed.
Object.isExtensible
Returns true if new properties can be added to the object. Sealed, frozen, and preventExtensions'd objects all return false; primitives always return false.