Deep Object Freeze in JavaScript

Level 5373 keystrokes

Implements deep freezing to make an object and all nested objects immutable.

JavaScript code

// deepFreeze recursively freezes an object and its nested objects
1function deepFreeze(obj) {
// Object.freeze prevents modification of the object's properties
2 Object.freeze(obj);
// Iterate through all property keys
3 for (const key of Object.keys(obj)) {
// Get the property value
4 const val = obj[key];
// Check if value is a non-null object that isn't already frozen
5 if (val !== null && typeof val === "object" && !Object.isFrozen(val)) {
// Recursively freeze nested objects
6 deepFreeze(val);
7 }
8 }
// Return the frozen object for chaining
9 return obj;
10}
11
// Create and deeply freeze a config object
12const config = deepFreeze({
// Nested object that will also be frozen
13 api: { url: "https://api.example.com" },
14 timeout: 5000
15});
16
// Access the nested URL
17console.log(config.api.url);
// Verify the nested object is frozen
18console.log(Object.isFrozen(config.api));

Output

https://api.example.com
true
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.

  • .× 11
  • (× 11
  • )× 11
  • ;× 7
  • =× 7
  • {× 5
  • }× 5
  • :× 4
  • "× 4
  • &× 4

More JavaScript examples at level 5

← JavaScript typing practice