JavaScript Reference ยท Object
Object.freeze()
Reference for JavaScript Object.freeze(): make an object immutable, understand shallow freezing, strict mode errors, arrays and how to freeze deeply.
Object.freeze() locks an object. After freezing you cannot add properties, remove properties, or change existing values, and you cannot redefine property attributes. Even the prototype cannot be replaced.
The freeze is shallow: only the object you pass is locked. Objects nested inside it stay changeable unless you freeze them too. The function changes the object in place and returns the same object.
const config = Object.freeze({ debug: false });
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
Object.freeze(obj)
| Name | Description |
|---|---|
obj |
The object to freeze. Non-objects are returned unchanged. |
Return value: the same object, now frozen.
Exceptions: none for ordinary objects. Freezing some typed arrays that have elements throws a TypeError, because their elements cannot be made read-only.
Usage notes
- Silent failure in sloppy mode. Writes to a frozen object are ignored. In strict mode, modules and class bodies they throw a
TypeError. Tests and linters are the place to catch them early. - Arrays can be frozen. Methods that change them (
push(),pop(),sort(),splice()) then throw aTypeError. Non-mutating methods such asmap()ortoSorted()still work. - Accessors still run. A getter or setter on a frozen object is not blocked. Freezing only fixes the property definitions, not what a setter does with other data.
- Frozen is permanent. There is no unfreeze. To change a frozen object, copy it (
{ ...obj }orstructuredClone()) and edit the copy. Object.freeze()versusconst.conststops a variable from being reassigned. Freezing stops an object from changing. They are independent.- Weaker alternatives:
Object.seal()allows changing existing values, andObject.preventExtensions()only blocks new properties. - Maps and Sets are not made read-only by freezing. Their entries are internal data, not properties.
- Performance: freezing is a one-off cost. Frozen objects are not meaningfully faster.
Browser support
Object.freeze() is available in every browser and JavaScript runtime.