How to freeze nested objects in javascript?

The function can be made much more terse in TS and ES2015.

import type { ReadonlyDeep } from 'type-fest';

export function deepFreeze<T>(o: T) {
  Object.values(o).forEach(v => Object.isFrozen(v) || deepFreeze(v));
  return Object.freeze(o) as ReadonlyDeep<T>;
}
  • Object.isFrozen now returns true for primitive objects.
  • Object.values instead of getOwnPropertyNames.

function deepFreeze (o) {
  Object.freeze(o);
  if (o === undefined) {
    return o;
  }

  Object.getOwnPropertyNames(o).forEach(function (prop) {
    if (o[prop] !== null
    && (typeof o[prop] === "object" || typeof o[prop] === "function")
    && !Object.isFrozen(o[prop])) {
      deepFreeze(o[prop]);
    }
  });

  return o;
};

https://github.com/substack/deep-freeze

It's public domain so you don't have to give credit :D

Tags:

Javascript