Shallow vs Deep Freeze

Med
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: Shallow vs Deep Freeze

Approach

Call Object.freeze on the top-level object, then recursively visit every property value. If a value is a non-null object, recursively deep-freeze it as well. This ensures nested objects become immutable, unlike the shallow native Object.freeze.

Complexity Analysis

Time
O(n) where n is the total number of nested properties
Space
O(d) where d is the nesting depth

Pattern

Deep Freeze

Why It Works

Object.freeze only prevents direct property modifications on the frozen object itself. Recursing into nested objects applies the same restriction at every level, making the entire object tree truly immutable.

Updated Mar 2026