#Objects#Immutability

Make Object Immutable

Freeze an object all the way down, because Object.freeze only handles the top level.

By Pratik RaiMedium

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

Input:

JSfile.javascript
1const config = deepFreeze({ api: { retries: 3 } }); 2config.api.retries = 99; 3config.api.retries;

Output:

3

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.

Goal: Freeze every level and return the same object.

Source

Frequently asked questions

Is Object.freeze deep?
No. It prevents writes to the object's own properties only, so any nested object stays fully mutable. That makes an unfrozen nested structure a false guarantee.
Why freeze before recursing?
Because it makes a self-referencing object terminate. By the time the walk reaches it again it is already frozen, so an `Object.isFrozen` check doubles as the cycle guard.
Why does writing to a frozen object fail silently?
In sloppy mode a failed write is ignored without any error. Only strict mode — including module code — throws a `TypeError`, which is why the behaviour surprises people in a console.
Is deep freezing expensive?
It walks and freezes every nested object once, which is real work on a large structure, and it cannot be undone. For big application state, structural sharing or an immutability library is usually a better fit.

Related Challenges

Continue learning with these related challenges

View All
JavaScript

Deep Clone

Copy a nested structure so nothing is shared — including the cases that break a naive recursion.

JavaScript · ES6Pratik Rai ·

JavaScript

Deep Equality

Compare two values structurally, because === only ever compares references.

JavaScript · ES6Pratik Rai ·

JavaScript

Array.prototype.groupBy

Group an array into buckets by a key function — now a real language feature as Object.groupBy.

JavaScript · ES6Pratik Rai ·