Immutable configuration
Protect configuration objects from accidental direct edits after initialization.
JavaScript · Function
Object.freeze() prevents extensions and locks an object's existing properties. It returns the same object reference and does not recursively freeze nested objects.
Object.freeze() makes an object non-extensible and locks its existing own property descriptors, returning the same object reference. It does not recursively freeze objects stored in those properties.
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({ theme: "dark", nested: { enabled: true } });
console.log(settings.theme); // "dark"
try {
settings.theme = "light";
} catch (error) {
console.log(error instanceof TypeError); // true
}
settings.nested.enabled = false; // Nested object is not frozen
console.log(settings.nested.enabled); // falseThe outer object rejects direct property changes, while its nested object remains mutable because freezing is shallow.
Protect configuration objects from accidental direct edits after initialization.
Expose a stable set of constants whose properties should not be reassigned.
Enforce read-only object properties at runtime in strict-mode code.
Object.freeze() prevents extensions and makes existing own properties non-configurable; data properties also become non-writable. It returns the object passed to it, so the operation changes that object in place.
Follow-up: How would you freeze nested data? Recursively call Object.freeze() on nested objects, because the built-in operation only affects immediate properties.
No new properties can be added, existing properties cannot be removed, and data-property values cannot be reassigned. The object's prototype also cannot be reassigned.
Follow-up: What happens when code attempts a forbidden operation? It may be ignored in non-strict code or raise TypeError, especially in strict mode.
Object.freeze() is shallow. If a frozen object's property contains another object, that nested object can still be changed unless it is frozen separately.
Follow-up: Does freezing an accessor property freeze the value returned by its getter? No; the getter and setter retain their accessor behavior, so the returned value may still vary.
Object.preventExtensions()Object.seal()Object.isFrozen()Object.getOwnPropertyDescriptors()