JavaScriptEasy
What is the purpose of Object.freeze()?
Object.freeze(obj) makes an object immutable at the top level: no properties can be added, removed or changed, and their attributes cannot be reconfigured; it returns the same object, now frozen.
What it blocks
- Adding new properties.
- Deleting properties.
- Changing values of existing data properties.
- Changing property descriptors (making them writable again, for example).
- Changing the object's prototype.
In strict mode (modules, classes) these attempts throw a TypeError; in sloppy mode they fail silently.
What it does not do
- It is shallow: nested objects and arrays are still mutable unless you freeze them too (a recursive "deep freeze").
- Setters on accessor properties can still run, and objects they reference can change.
- It does not create a copy.
- Frozen
Map/Setobjects can still change their entries, because those are stored internally, not as properties.
Use cases
- Constants and configuration that must not be changed:
const ROLES = Object.freeze({ ADMIN: "admin", USER: "user" }), an enum-like object. - Catching accidental mutation of state in development (deep-freeze state in tests or reducers).
- Library defaults that callers must not modify.
Related
Object.isFrozen(obj)to check.Object.seal(allows value changes) andObject.preventExtensions(only blocks additions).- In TypeScript,
as constandReadonly<T>give compile-time immutability with zero runtime cost; useObject.freezewhen you need runtime protection.
Code example
js
1"use strict";23const ROLES = Object.freeze({ ADMIN: "admin", EDITOR: "editor" });45for (const attempt of [6 () => (ROLES.ADMIN = "root"), // change7 () => (ROLES.GUEST = "guest"), // add8 () => delete ROLES.EDITOR, // delete9]) {10 try {11 attempt();12 } catch (e) {13 console.log(e.name); // TypeError (x3) in strict mode14 }15}16console.log(ROLES, Object.isFrozen(ROLES)); // { ADMIN: "admin", EDITOR: "editor" } true1718// Shallow: nested objects are still mutable19const config = Object.freeze({ api: { url: "https://api.example.com" }, flags: ["beta"] });20config.api.url = "https://evil.example";21config.flags.push("debug");22console.log(config.api.url, config.flags); // https://evil.example ["beta", "debug"]2324// Deep freeze recursively25function deepFreeze(obj) {26 for (const value of Object.values(obj)) {27 if (value && typeof value === "object" && !Object.isFrozen(value)) deepFreeze(value);28 }29 return Object.freeze(obj);30}31const safeConfig = deepFreeze({ api: { url: "https://api.example.com" }, flags: ["beta"] });32try {33 safeConfig.flags.push("debug");34} catch (e) {35 console.log("deep frozen:", e.name); // deep frozen: TypeError36}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.