javascript 30 lines · 6 steps

Recursively freezing a nested object

A small recursive helper walks every property and freezes each object so a whole config tree becomes deeply immutable.

Explained by highlit
1function deepFreeze(obj) {
2 const propNames = Reflect.ownKeys(obj);
3 
4 for (const name of propNames) {
5 const value = obj[name];
6 if ((value && typeof value === 'object') || typeof value === 'function') {
7 deepFreeze(value);
8 }
9 }
10 
11 return Object.freeze(obj);
12}
13 
14const config = deepFreeze({
15 env: 'production',
16 server: {
17 host: '0.0.0.0',
18 port: 8080,
19 tls: {
20 enabled: true,
21 ciphers: ['TLS_AES_256_GCM_SHA384'],
22 },
23 },
24 featureFlags: {
25 betaSearch: false,
26 darkMode: true,
27 },
28});
29 
30export default config;
01 / 01
STEP 01

Walkthrough

Space play ←→ step click any line
Three takeaways
  1. 1Object.freeze is shallow, so nested objects need recursion to become truly immutable.
  2. 2Reflect.ownKeys captures string and symbol keys, including non-enumerable ones, unlike a plain for...in.
  3. 3Freezing children before the parent guarantees the entire tree is locked by the time the top-level call returns.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Recursively freezing a nested object — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code