Freezing objects with Object.freeze

Object.freeze(value) makes every own property of an object read-only and non-configurable and stops new properties from being added. It returns the same object, so it is usually written around a literal: const config = Object.freeze({ ... });. Object.isFrozen answers whether the work was done.

A freeze is shallow, and in a file without strict mode a refused write is silent. Both facts cause the same surprise: the program looks like it changed a value, and later lines read the old one. JavaScript fixes the second with strict mode, which is the default in a module, and the first has to be fixed by hand.

Object.freeze

The program below freezes a settings object and then writes to two of its properties. The file is a CommonJS script with no use strict directive, which matters for the next section: in this mode the runtime ignores a write to a read-only property and carries on.

const config = Object.freeze({ debug: true, port: 8080 }); config.debug = false; config.port = 80; console.log('frozen:', Object.isFrozen(config)); console.log('debug:', config.debug); console.log('port:', config.port);

node freeze.cjs

frozen: true
debug: true
port: 8080

The object reports itself frozen, and both writes did nothing at all: no error, no warning, no new value. This is the worst of the three possible answers, because the source says one thing and the output another. A file that is strict turns the same two lines into errors.

Silent in sloppy mode, an error in strict

A module is strict by its nature, so a .mjs file needs no directive. The write below throws TypeError with the property name and the object in the message, which the catch block prints before the program continues.

const config = Object.freeze({ debug: true, port: 8080 }); try { config.debug = false; } catch (error) { console.log(error.name + ': ' + error.message); } console.log('debug:', config.debug); console.log('frozen:', Object.isFrozen(config));

node freeze_strict.mjs

TypeError: Cannot assign to read only property 'debug' of object '#<Object>'
debug: true
frozen: true

The value still did not change, and the difference is that the program said so out loud. Outside a try block the same error ends the program with a non-zero status, which no build step has to notice: the failure arrives at the line that made it. The lesson on strict mode lists what else the mode changes.

A freeze is shallow

Object.freeze touches the own properties of one object. A property whose value is another object is made non-writable, which means the property keeps pointing at that object; the inner object itself is not frozen, and its properties stay writable.

const settings = Object.freeze({ theme: 'dark', window: { width: 800 }, }); try { settings.theme = 'light'; } catch (error) { console.log(error.name + ': ' + error.message); } settings.window.width = 1200; console.log('theme:', settings.theme); console.log('width:', settings.window.width); console.log('inner frozen:', Object.isFrozen(settings.window));

node shallow_freeze.mjs

TypeError: Cannot assign to read only property 'theme' of object '#<Object>'
theme: dark
width: 1200
inner frozen: false

The write to the top level threw and the write one level down went through, because only the outer object was frozen. The last line states the cause. A frozen object with an open door inside is a common source of a bug that looks impossible: the object is frozen, and its state still changes.

A deep freeze by hand

There is no Object.deepFreeze. The walk is short enough to write: freeze the children first, then the object, so that a child added after the freeze cannot slip in. The function below stops at primitives, walks the own keys with Object.keys, and returns the value so a binding can keep the result.

function deepFreeze(value) { if (value === null || typeof value !== 'object') { return value; } for (const key of Object.keys(value)) { deepFreeze(value[key]); } return Object.freeze(value); } const state = deepFreeze({ user: { name: 'Ada' }, tags: ['math'] }); try { state.user.name = 'Grace'; } catch (error) { console.log(error.name + ': ' + error.message); } try { state.tags.push('code'); } catch (error) { console.log(error.name + ': ' + error.message); } console.log('name:', state.user.name); console.log('tags:', state.tags.join(', ')); console.log( 'all frozen:', Object.isFrozen(state), Object.isFrozen(state.user), Object.isFrozen(state.tags), );

node deep_freeze.mjs

TypeError: Cannot assign to read only property 'name' of object '#<Object>'
TypeError: Cannot add property 1, object is not extensible
name: Ada
tags: math
all frozen: true true true

Both writes failed, one on a property and one on the length of a frozen array, and the three isFrozen answers agree. Two limits stay: a value that holds itself sends the walk round for ever, so a real helper keeps a Set of seen objects, and a frozen Map still accepts set, because the entries live inside the collection rather than in its properties.

Exercises

  1. Run freeze.cjs with node --use-strict freeze.cjs. How does the output change, and which of the two programs on this page does it now match?
  2. Add a new property config.timeout = 1000 to freeze_strict.mjs. Which message does the catch print?
  3. Freeze the inner object in shallow_freeze.mjs as well and run it again. Which lines of the output change?
  4. Give deepFreeze a Set of visited objects so that a value which contains itself does not loop. Test it with state.self = state before the freeze.
  5. Call Object.freeze on an array and then on a Map, and try to add an entry to each. Which one refuses?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does Object.freeze change about an object?

    Answer

    Its own properties become read-only and no new ones may be added

    The freeze covers the own properties of one object, and nested objects keep their own state.

  2. What does Object.freeze return?

    Answer

    The same object, now frozen

    The function freezes in place and returns the argument, which is why it is written around a literal.

  3. What does this module print? const config = Object.freeze({ debug: true }); try { config.debug = false; } catch (error) { console.log(error.name); }

    Answer

    TypeError

    The file is a module, so strict mode turns the refused write into a TypeError.

  4. What does this program print? const settings = Object.freeze({ inner: { n: 1 } }); settings.inner.n = 2; console.log(settings.inner.n);

    Answer

    2

    The freeze is shallow, so the inner object is not frozen and its property is writable.

  5. What does a refused write to a frozen object do in a file with no strict mode?

    Answer

    It is ignored and the program continues

    Sloppy mode ignores the write, which is why a frozen object is safest in a module.

  6. What does this program print? const settings = Object.freeze({ n: 1 }); console.log(Object.isFrozen(settings));

    Answer

    true

    isFrozen reports the state the object is in, and Object.freeze has just set it.

  7. Why does a deep freeze walk the children before the parent?

    Answer

    Because a child added after the freeze would otherwise stay writable

    The walk must reach every object while the properties are still writable, so the parent is frozen last.

  8. What does Object.freeze do to a Map that is passed to it?

    Answer

    It blocks new properties but set still adds entries

    Map entries live inside the collection, not in its properties, so freeze does not reach them.

  9. What does this program print? const config = Object.freeze({ debug: true }); try { config.debug = false; } catch { // the module refuses the write } console.log(config.debug);

    Answer

    true

    The write is refused in either mode, so the property keeps the value it was frozen with.

  10. Which pair of calls makes an object and its nested object both read-only?

    Answer

    Object.freeze(outer) and Object.freeze(outer.inner)

    Each freeze covers one object, so the nested object needs its own call or a recursive helper.

The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev