Deep Clone
Copy a nested structure so nothing is shared — including the cases that break a naive recursion.
JavaScript · ES6 — Pratik Rai ·
Freeze an object all the way down, because Object.freeze only handles the top level.
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.
Input:
JSfile.javascript1const config = deepFreeze({ api: { retries: 3 } }); 2config.api.retries = 99; 3config.api.retries;
Output:
3
Object.freeze alone would have left the nested object writable.
Object.isFrozen becomes your cycle guard for free.Object.freeze stops writes to an object's own properties and nothing deeper. A frozen config with a nested object is still fully mutable one level down, which makes it a false guarantee.
Freeze, then recurse.
JSfile.javascript1function deepFreeze(obj) { 2 if (obj === null || typeof obj !== 'object' || Object.isFrozen(obj)) return obj; 3 Object.freeze(obj); 4 Object.getOwnPropertyNames(obj).forEach((key) => deepFreeze(obj[key])); 5 return obj; 6}
Order matters. Freezing before recursing means a self-referencing object is already frozen when the walk reaches it again, so Object.isFrozen doubles as the cycle guard and no extra bookkeeping is needed.
In sloppy mode a write to a frozen property fails silently — no error, no change — which is why this surprises people. Only strict mode throws. Deep-freezing a large object is also not free: every nested object is walked and frozen once, and freezing is permanent.
Goal: Freeze every level and return the same object.
Object.isFrozen check doubles as the cycle guard.TypeError, which is why the behaviour surprises people in a console.Continue learning with these related challenges
Copy a nested structure so nothing is shared — including the cases that break a naive recursion.
JavaScript · ES6 — Pratik Rai ·
Compare two values structurally, because === only ever compares references.
JavaScript · ES6 — Pratik Rai ·
Group an array into buckets by a key function — now a real language feature as Object.groupBy.
JavaScript · ES6 — Pratik Rai ·
Copy a nested structure so nothing is shared — including the cases that break a naive recursion.
JavaScript · ES6
Pratik Rai ·
Compare two values structurally, because === only ever compares references.
JavaScript · ES6
Pratik Rai ·
Group an array into buckets by a key function — now a real language feature as Object.groupBy.
JavaScript · ES6
Pratik Rai ·