1. Home
  2. Blog
  3. Software Development

Software Development

Object Freeze in JavaScript: Shallow vs Deep, Seal and const

Object freeze in JavaScript makes an object read-only: no new properties, no changes, no deletions. But it is shallow, it fails silently in some code and loudly in other code, and it does nothing to a Map or a Date. We tested Object.freeze, Object.seal, preventExtensions and const side by side in Node.js 24, built a deep freeze, and measured the cost.

9 min read
Object freeze in JavaScript: shallow vs deep, seal and const

Key takeaways

  • Object freeze (Object.freeze(obj)) blocks adding, changing and deleting properties, but only one level deep.
  • In an ES module, writing to a frozen object threw a TypeError; in a plain CommonJS script, the same write was ignored silently.
  • A frozen object’s nested object and array were still changeable until we wrote a recursive deep freeze.
  • Freezing a Map or a Date did not stop map.set() or date.setFullYear().

Shared configuration, constants, application state and default options are all objects that should not change after they are created. JavaScript objects are mutable by default, and a single accidental assignment somewhere in a large codebase can change behaviour everywhere. Object freeze lets you lock an object so such mistakes are caught or prevented, but it has rules that surprise even experienced developers.

All examples ran in Node.js v24.22.1. Browsers behave the same; the strict-mode differences apply everywhere.

const is not freeze

const c = { a: 1 };
c.a = 2;            // allowed: c.a is now 2
c = {};             // TypeError: Assignment to constant variable.

const protects the variable: it can never point to a different object. It does nothing to the object itself, so its properties can still change. Freezing protects the object. The two are complementary, and constants that should be truly fixed usually need both.

What Object.freeze does

const f = Object.freeze({ a: 1, nested: { b: 1 }, list: [1, 2] });
Object.isFrozen(f)                         // true
Object.getOwnPropertyDescriptor(f, "a")
// { value: 1, writable: false, enumerable: true, configurable: false }

Freezing makes the object non-extensible (no new properties) and marks every existing property as non-writable and non-configurable (no changes, no deletions, no redefinition). It returns the same object, so const CONFIG = Object.freeze({...}) is a common one-liner. The change cannot be undone; there is no “unfreeze”.

Silent or loud: strict mode decides

// CommonJS script (non-strict)
f.a = 99; f.z = 1; delete f.a;
f.a, f.z, "a" in f        // 1 undefined true   (all ignored, no error)

// strict mode, and every ES module
f.a = 99    // TypeError: Cannot assign to read only property 'a' of object '#<Object>'
f.z = 1     // TypeError: Cannot add property z, object is not extensible
delete f.a  // TypeError: Cannot delete property 'a' of #<Object>

This was the most important result in our tests. In non-strict code, writes to a frozen object simply did nothing, which can hide bugs for a long time: the program keeps running with an old value. In strict mode they throw, pointing straight at the faulty line. Our first test file was an ES module (.mjs), and it crashed on the very first write, because modules and class bodies are always strict. Use modules or "use strict" so frozen objects fail loudly.

Object.freeze is shallow

f.nested.b = 2;
f.list.push(3);
f.nested.b, f.list            // 2 [ 1, 2, 3 ]
Object.isFrozen(f.nested)     // false

Freezing only affects the object’s own properties. The nested property cannot be pointed at a different object, but the nested object itself is still fully mutable, and so is the array. This catches people out with configuration objects, which are almost always nested.

Object.seal and Object.preventExtensions

const s = Object.seal({ a: 1 });
s.a = 2; s.z = 3; delete s.a;
s.a, s.z, Object.isSealed(s)      // 2 undefined true

const p = Object.preventExtensions({ a: 1 });
p.a = 2; p.z = 3; delete p.a;
p.a, p.z                          // undefined undefined

There are three levels of protection. preventExtensions only blocks new properties: our object allowed the change to a and then the deletion. seal also blocks deletion and reconfiguration but still allows existing values to change, which suits objects with a fixed shape whose values update. freeze blocks everything.

Comparison table

Operation const preventExtensions seal freeze
Reassign the variable No Yes Yes Yes
Add properties Yes No No No
Delete properties Yes Yes No No
Change values Yes Yes Yes No
Nested objects protected No No No No

Deep freeze

function deepFreeze(o) {
  for (const k of Reflect.ownKeys(o)) {
    const v = o[k];
    if (v && typeof v === "object" && !Object.isFrozen(v)) deepFreeze(v);
  }
  return Object.freeze(o);
}

const d = deepFreeze({ nested: { b: 1, deeper: { c: [1] } } });
d.nested.deeper.c.push(2)   // TypeError: Cannot add property 1, object is not extensible
Object.isFrozen(d.nested.deeper.c)   // true

A recursive helper freezes every nested object and array. Reflect.ownKeys includes symbol keys, and the isFrozen check stops infinite loops on circular references and avoids refreezing shared objects. Add functions to the check if your objects contain functions with properties. Be careful freezing objects you do not own, such as library instances: freezing them can break the library.

Frozen arrays

const arr = Object.freeze([3, 1, 2]);
arr.sort()        // TypeError: Cannot assign to read only property '0' of object '[object Array]'
arr.toSorted()    // [ 1, 2, 3 ]   (new array)
arr.map(x => x * 2)   // [ 6, 2, 4 ]

Mutating methods such as sort, push, splice and reverse throw on a frozen array. Non-mutating methods work, and since ES2023 there are copying versions of the mutating ones: toSorted, toReversed, toSpliced and with. Frozen arrays pair naturally with these; see our array methods guide.

Map, Set and Date ignore freeze

const m = Object.freeze(new Map([["k", 1]]));
m.set("k", 2);  m.get("k")         // 2

const dt = Object.freeze(new Date(0));
dt.setFullYear(2030);  dt.getUTCFullYear()   // 2030

Map, Set and Date keep their data in internal slots, not in properties, so freezing the object does not stop their methods from changing it. If you need read-only collections, wrap them in an object that exposes only read methods, or use plain frozen objects and arrays. The differences between maps and objects are covered in our Map vs object guide.

Classes, private fields and getters

class P { #x = 1; inc() { return ++this.#x; } }
const fp = Object.freeze(new P());
fp.inc()          // 2   (private fields are not properties)

Object.freeze({ _v: 1, get v() { return this._v; } }).v    // 1

Freezing a class instance did not stop its #private field from changing, because private fields are not ordinary properties. Getters still run normally. A common pattern for immutable value objects is to set fields in the constructor and call Object.freeze(this) at the end; our JavaScript classes guide covers private fields in more depth.

Copies are not frozen

const sc = structuredClone(f);  sc.a = 5;      // 5, Object.isFrozen(sc) is false
const spread = { ...f, a: 7 };                  // 7, Object.isFrozen(spread) is false

Copying a frozen object with spread syntax or structuredClone produces a normal, mutable object. That is useful for the “update by copying” style used with immutable state: freeze the current state, create a modified copy, freeze that. More on copying in our deep copy guide. If you want writes blocked with custom logic instead, a Proxy can intercept them, but note that proxies must respect a frozen target’s rules.

Performance

20 million property reads (after warm-up): frozen 13.9 to 17.6 ms, plain 13.8 to 16.6 ms
100,000 objects: Object.freeze 12 ms, deepFreeze 53 ms

Reading from frozen objects was as fast as from plain ones across three rounds. Our first, single-round measurement suggested frozen reads were slower, but that was JIT warm-up order, not freezing; repeated rounds removed the difference. Freezing itself is cheap, about 0.1 microseconds per small object, and deep freezing costs more in proportion to the number of nested objects. For large state trees updated many times per second, consider freezing only in development builds.

When to use Object.freeze

  • Constants and configuration that must never change at runtime: deep freeze them once at start-up.
  • Enum-like objects: const Color = Object.freeze({ RED: "red", GREEN: "green" }).
  • Default options passed to many functions, so one caller cannot change them for everyone.
  • Immutable state in reducers, to catch accidental mutation early (in strict mode).
  • Not for security: freezing prevents mistakes; it does not protect secrets from code running on the page.

Final thoughts

Object freeze is the strongest built-in way to make a JavaScript object read-only, but our tests showed its limits clearly: it is shallow, it fails silently outside strict mode, and Map, Set, Date and private fields ignore it. Combine const with a deep freeze for configuration, run in modules or strict mode so violations throw, use seal when values should change but shape should not, and remember that copies start out mutable.

Frequently asked questions

What does Object.freeze do in JavaScript?

It prevents adding, changing and deleting the properties of an object. The object becomes read-only at the top level, and Object.isFrozen returns true.

What is the difference between const and Object.freeze?

const stops the variable from being reassigned to a different value. Object.freeze stops the object itself from being changed. A const object can still be modified unless it is also frozen.

Does Object.freeze freeze nested objects?

No. It is shallow. Nested objects and arrays stay mutable unless you freeze them too, usually with a recursive deep freeze function.

What is the difference between Object.seal and Object.freeze?

Both block adding and deleting properties. Seal still allows existing values to change, while freeze makes them read-only as well.

Why does changing a frozen object not throw an error?

Outside strict mode, writes to frozen objects fail silently. In strict mode and in ES modules, the same write throws a TypeError.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Confusion Matrix Explained: Precision, Recall, F1 and Thresholds in Python

Confusion matrix explained with Python: TP, FP, FN, TN, precision, recall, F1, the accuracy trap, threshold choice by cost and…

Read article →
Software Development

API Pagination: Offset vs Cursor vs Keyset, Tested on 1 Million Rows

API pagination explained: offset vs keyset and cursor pagination timed on 1 million rows, duplicates when data changes, the ties…

Read article →
DevOps

Git Submodule Explained: Add, Clone, Update and Remove Safely

Git submodule explained: add, clone, update –init, update –remote, the detached HEAD trap, foreach and clean removal, tested step by…

Read article →
Test Automation

Pytest tmp path Explained: tmp_path, tmp_path_factory and Temp Files

Pytest tmp_path explained: per-test temporary folders, tmp_path_factory for shared files, monkeypatch.chdir, legacy tmpdir, retention and basetemp.

Read article →
Software Testing

Test Case Prioritization: 6 Techniques Compared With APFD

Test case prioritization compared: risk, coverage, cost, history and random orders scored with APFD and time to find all faults…

Read article →
Databases & SQL

Full Text Search in SQL: FTS5, Ranking, Phrases and Speed

Full text search in SQL with SQLite FTS5: MATCH queries, phrases, prefixes, NEAR, stemming, BM25 ranking, snippets, two gotchas and…

Read article →
Databases & SQL

Generated Columns in SQL: Virtual vs Stored, Indexes and Limits

Generated columns in SQL explained: virtual vs stored, automatic updates, write errors, storage cost, indexing, JSON fields and support in…

Read article →
Software Development

Object Freeze in JavaScript: Shallow vs Deep, Seal and const

Object freeze in JavaScript explained: freeze vs seal vs const, strict mode errors, shallow vs deep freeze, frozen arrays, Map…

Read article →
Software Development

Python hashlib: SHA-256, File Hashes, HMAC and Password Hashing

Python hashlib explained: SHA-256 for strings and files, algorithm speeds, why passwords need PBKDF2 or scrypt, safe verification and HMAC…

Read article →
Software Development

Python UUID Explained: uuid1, uuid4, uuid5, uuid7 and Database Keys

Python UUID explained: uuid4, uuid5, uuid1 privacy, time-ordered uuid7, parsing, storage formats and UUIDs as database keys, tested on Python…

Read article →
Artificial Intelligence

Random Forest in Python: Bagging, Feature Sampling and OOB From Scratch

Random forest in Python from scratch: bootstrap sampling, feature sampling, number of trees, out-of-bag evaluation and impurity vs permutation importance.

Read article →
Software Development

MIME Types Explained: Content-Type, nosniff and a Common Types List

MIME types explained and tested in a browser: Content-Type, nosniff, scripts and stylesheets with wrong types, a common MIME types…

Read article →
DevOps

Git Clean Explained: Remove Untracked Files Without Regret

Git clean explained with dry runs: -n, -f, -d, -x, -X, exclusions, paths, nested repositories and interactive mode, plus a…

Read article →
Test Automation

Pytest approx: Comparing Floats With rel, abs and Collections

Pytest approx explained: default tolerances, the near-zero trap, rel and abs, lists and dicts, NaN, NumPy, and how it differs…

Read article →
Software Testing

Accessibility Testing: WCAG Checklist, Automated Tools and Manual Checks

Accessibility testing explained: WCAG basics, an axe-core scan of a broken and a fixed page, what automation missed, contrast checks…

Read article →
Databases & SQL

SQL UNPIVOT: Turn Columns Into Rows, 4 Ways Tested

SQL UNPIVOT explained: turn columns into rows with UNION ALL, CROSS JOIN with CASE, JSON functions or native UNPIVOT, with…

Read article →
Software Development

Intl NumberFormat in JavaScript: Currency, Compact, Percent and Units

Intl.NumberFormat in JavaScript: locales, currency, compact notation, percent, units, rounding, formatToParts, the non-breaking space trap and formatter reuse.

Read article →
Databases & SQL

SQL EXPLAIN Plan: How to Read Query Plans and Fix Slow Queries

SQL EXPLAIN plan explained: read scans, index searches, covering indexes and temporary sorts, with before and after timings for five…

Read article →
Artificial Intelligence

Decision Tree in Python: Gini, Entropy and Overfitting From Scratch

Decision tree in Python from scratch: Gini impurity, entropy, information gain, best splits, readable rules, and how depth and leaf…

Read article →
DevOps

Git Blame Explained: Find Who Changed a Line, and Why

Git blame explained with a real repository: ignore whitespace, line ranges and functions, ignore-revs files for formatting commits, moved code…

Read article →
Test Automation

Pytest Benchmark: Measure Speed and Catch Performance Regressions

Pytest benchmark tutorial: the benchmark fixture, reading results, parametrized and pedantic benchmarks, saving baselines and failing the build on regressions.

Read article →
Software Testing

Defect Density: Formula, Worked Examples and How to Use It

Defect density explained: the formula, a five-module worked example, per KLOC vs per function point, severity weighting, defect removal efficiency…

Read article →
Databases & SQL

Case Insensitive Search in SQL: LOWER, LIKE, COLLATE and Indexes

Case insensitive search in SQL: LOWER, LIKE, COLLATE NOCASE and expression indexes compared with query plans, plus accented letters and…

Read article →
Databases & SQL

ON DELETE CASCADE in SQL: CASCADE vs SET NULL vs RESTRICT

ON DELETE CASCADE in SQL tested: CASCADE vs SET NULL vs RESTRICT, multi-level cascades, the SQLite foreign key pragma, row…

Read article →
Artificial Intelligence

Logistic Regression in Python: Sigmoid, Log Loss and Gradient Descent From Scratch

Logistic regression in Python from scratch: sigmoid, log loss, gradient descent, odds ratios, thresholds, sigmoid overflow and separable data, tested…

Read article →
DevOps

Git Worktree Explained: Work on Two Branches at Once

Git worktree explained: add, list, remove, prune, lock and detached worktrees, a hotfix workflow, and the errors you will hit,…

Read article →
Test Automation

Pytest ini Explained: addopts, markers, testpaths and Precedence

Pytest ini explained: testpaths, addopts, strict markers, xfail_strict, filterwarnings, minversion, config file precedence and command-line overrides, tested.

Read article →
Software Testing

Test Estimation Techniques: WBS, Three Point PERT and Monte Carlo

Test estimation techniques worked through: WBS, three point PERT, total uncertainty, a Monte Carlo check, percentage rules and Wideband Delphi.

Read article →
Artificial Intelligence

Linear Regression in Python: Least Squares From Scratch, With R Squared

Linear regression in Python from scratch: closed form, NumPy least squares and gradient descent, R squared, RMSE, outliers and curved…

Read article →
DevOps

Git Remote Explained: Add, Set-URL, Rename, Remove and Push URLs

Git remote explained: add, set-url, separate push URLs, rename, remove and prune, plus how to avoid leaking tokens in remote…

Read article →
Test Automation

Pytest Mock: mocker.patch, spy, side_effect and autospec Explained

Pytest mock explained: mocker.patch, return_value, side_effect, spy, autospec and PropertyMock, with tested examples for APIs, clocks and retries.

Read article →
Software Testing

System Testing Explained: Types, Process and a Real End-to-End Example

System testing explained: types, entry and exit criteria, the process, and a real end-to-end test suite run against a small…

Read article →
Artificial Intelligence

Naive Bayes Classifier Explained: Build a Spam Filter in Python

Naive Bayes classifier explained by building a spam filter in Python: Bayes rule, the naive assumption, Laplace smoothing, log probabilities…

Read article →
DevOps

Git Branch Explained: Create, Switch, Rename, Delete and Recover

Git branch explained with tested commands: list, create, switch, rename, delete, merged checks, recovering deleted branches, remote tracking and naming.

Read article →
Test Automation

Pytest raises: Testing Exceptions, match and excinfo

Pytest raises explained with tested examples: match regexes, excinfo, custom and chained exceptions, parametrized error cases, pytest.warns and common mistakes.

Read article →
Software Testing

Non Functional Testing: Types, Metrics and a Real Load Test

Non functional testing explained: 10 key types, measurable requirements, latency percentiles and what a small real load test revealed about…

Read article →