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/Set objects 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) and Object.preventExtensions (only blocks additions).
  • In TypeScript, as const and Readonly<T> give compile-time immutability with zero runtime cost; use Object.freeze when you need runtime protection.

Code example

js
1"use strict";
2
3const ROLES = Object.freeze({ ADMIN: "admin", EDITOR: "editor" });
4
5for (const attempt of [
6 () => (ROLES.ADMIN = "root"), // change
7 () => (ROLES.GUEST = "guest"), // add
8 () => delete ROLES.EDITOR, // delete
9]) {
10 try {
11 attempt();
12 } catch (e) {
13 console.log(e.name); // TypeError (x3) in strict mode
14 }
15}
16console.log(ROLES, Object.isFrozen(ROLES)); // { ADMIN: "admin", EDITOR: "editor" } true
17
18// Shallow: nested objects are still mutable
19const 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"]
23
24// Deep freeze recursively
25function 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: TypeError
36}

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.

Open in study app