Skip to content
jshacks.dev
Functions

Deep freeze an object recursively

Deep freeze an object recursively in JavaScript so nested objects and arrays become read only too, and see the strict mode errors it produces.

1 min read
Summarize in AI

Object.freeze stops at the first level. Nested objects can still be changed, so a frozen config is not really frozen. Freeze the children as well.

JavaScript
'use strict';

const deepFreeze = (obj) => {
  Object.freeze(obj);
  for (const value of Object.values(obj)) {
    if (value && typeof value === 'object' && !Object.isFrozen(value)) deepFreeze(value);
  }
  return obj;
};

const config = deepFreeze({ db: { host: 'localhost', ports: [5432] } });

try {
  config.db.host = 'other';
} catch (error) {
  console.log(error.message);
}

try {
  config.db.ports.push(6432);
} catch (error) {
  console.log(error.message);
}
Text
Cannot assign to read only property 'host' of object '#<Object>'
Cannot add property 1, object is not extensible

The object is frozen before its children are visited, so a cycle stops at the first object that is already frozen and does not loop forever. In strict mode, which the first line turns on, writing to a frozen object throws. In sloppy mode the write is ignored without any message. See Object.freeze.

Freezing a non-empty typed array throws, and Map and Set can still be changed through their methods, because freezing does not touch their internal data. Freeze marks the object; it does not make it deeply immutable by type.

Taggednode 24
Share

More snippets

Functions

Write a once function

Write a once function in JavaScript that runs a callback a single time and returns the cached result after that. Works in any Node.js, ES2015 or later.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.