Protect configuration
Expose configuration objects that callers should not modify.
JS Puzzles · Const
Object.freeze() prevents extensions and makes an object's existing properties non-writable and non-configurable. It returns the same object, while nested objects remain mutable unless frozen separately.
Object.freeze marks an object as non-extensible and makes its existing data properties non-writable and non-configurable. It returns the same object rather than creating a copy; referenced nested objects remain independently mutable unless they are frozen too.
Object.freeze(obj)| Name | Type | Description |
|---|---|---|
obj | object | The object to freeze. |
The object that was passed to the function.
"use strict";
const settings = Object.freeze({
mode: "dark",
nested: { enabled: true },
});
settings.mode = "light"; // TypeError
settings.nested.enabled = false; // Allowed: nested is not frozen
console.log(settings.mode); // "dark"
console.log(settings.nested.enabled); // falseThe outer object is frozen, but freezing does not recursively freeze objects referenced by its properties.
Expose configuration objects that callers should not modify.
Prevent accidental mutation of shared constants or state snapshots.
Lock an API object's shape and property descriptors before handing it to other code.
Object.freeze prevents extensions and sets existing data properties to non-writable and non-configurable. It also prevents changing the object's prototype. The method returns the same object it receives.
Follow-up: Does it deep-freeze nested objects? No. A nested object must be passed to Object.freeze separately, typically through a deliberate recursive utility.
In strict mode, attempts to add, delete, or assign to restricted properties throw TypeError. In non-strict code, such operations can fail silently.
Follow-up: Would a setter on a frozen object stop working? No. Accessor setters can still be invoked because freezing does not remove accessor behavior.
Object.freeze returns the input object, not a new copy, so identity is preserved. Freezing also makes the object non-extensible and locks the relevant property descriptors.
Follow-up: How does Object.freeze differ from Object.seal? Sealing prevents extensions and property deletion, while freezing additionally makes existing data properties immutable.
Object.seal()Object.preventExtensions()Object.isFrozen()Object.isSealed()Object.defineProperty()