Skip to the solution
MediumLow-Level DesignAsked in 20246 min read

Deep Freeze Object

603 views

The problem

Problem, as an interviewer would state it: "Implement deepFreeze(obj) — unlike Object.freeze(), which only freezes an object's OWN top-level properties, this must recursively freeze every nested object too, so mutation is blocked at every level."

Examples:

Code
const frozen = deepFreeze({ a: 1, nested: { b: 2 } });
frozen.nested.b = 99; // silently fails (or throws in strict mode) -- b is still 2

Clarifying questions expected:

  • Does plain Object.freeze() alone already handle nested objects, or is that the specific real gap this question is testing?
  • Should arrays be recursed into the same way as plain objects?
  • What should happen with a circular reference — recurse forever, or detect and stop?

Code / implementation expected: Yes — real, direct proof that mutation is blocked at the top level, a nested level, AND a deeply nested level, contrasted directly against a naive, real Object.freeze() call that fails to protect nested data.

  • object
  • recursion

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: deepFreeze() blocks mutation at every nesting level, contrasted against a naive Object.freeze() that fails on nested data

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 109 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

HTML tag tree parser

Continue