Deep Object Freeze in JavaScript

Level 5411 keystrokes

Deep freeze recursively freezes all nested objects, making them fully immutable.

JavaScript code

// Deep freeze function that handles nested objects
1function deepFreeze(obj) {
// Iterate through all properties
2 Object.keys(obj).forEach(key => {
// If property is an object (and not null), recurse
3 if (typeof obj[key] === "object" && obj[key] !== null) {
4 deepFreeze(obj[key]);
5 }
6 });
// Freeze the current object and return it
7 return Object.freeze(obj);
8}
9
// Create a deeply frozen config object
10const config = deepFreeze({
11 api: { url: "https://api.example.com", timeout: 5000 },
12 debug: false
13});
14
// Read frozen value - works fine
15console.log(config.api.url);
// Try to modify a nested property - ignored (a TypeError in strict mode)
16config.api.url = "changed";
// Try to modify a top-level property - also ignored
17config.debug = true;
// Values remain unchanged: the original url and false
18console.log(config.api.url);
19console.log(config.debug);

Output

https://api.example.com
https://api.example.com
false
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this JavaScript code and how often they appear.

  • .× 16
  • (× 10
  • )× 10
  • ;× 9
  • =× 9
  • "× 6
  • :× 5
  • {× 5
  • }× 5
  • [× 3

More JavaScript examples at level 5

← JavaScript typing practice