Make Object Immutable

ObjectsImmutabilityRecursion

Write deepFreeze(obj) that freezes an object and everything nested inside it, then returns the same object.

After freezing, writing to a property at any depth must not change it. A structure that contains itself must not recurse forever.

Examples

Example 1
Input
const config = deepFreeze({ api: { retries: 3 } });
config.api.retries = 99;
config.api.retries;
Output
3
Explanation
Object.freeze alone would have left the nested object writable.

Constraints

  • Values are objects, arrays and primitives

Notes

  • In sloppy mode a write to a frozen property fails silently; only strict mode throws.
  • Freeze before recursing and `Object.isFrozen` becomes your cycle guard for free.

Hints

Read the full write-up for Make Object Immutable
</>JavaScript
Loading editor…
Test Result
Run your code, or Submit to test it