Deep Object Freeze in JavaScript

Level 5339 keystrokes

Deep freeze recursively freezes an object and all its nested objects to prevent any modifications.

JavaScript code

// Define recursive deepFreeze function
1function deepFreeze(obj) {
// Iterate over all keys in the object
2 Object.keys(obj).forEach(key => {
// Check if value is an object (not null)
3 if (typeof obj[key] === "object" && obj[key] !== null) {
// Recursively freeze nested object
4 deepFreeze(obj[key]);
5 }
6 });
// Freeze and return the object
7 return Object.freeze(obj);
8}
// Create deeply frozen config object
9const config = deepFreeze({
// Nested object that will also be frozen
10 api: { url: "https://api.example.com" },
// Primitive property
11 debug: true
12});
// Check if the root object is frozen: true
13console.log(Object.isFrozen(config));
// Check if the nested object is also frozen: true
14console.log(Object.isFrozen(config.api));

Output

true
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
  • .× 10
  • =× 7
  • ;× 6
  • {× 5
  • }× 5
  • :× 4
  • "× 4
  • [× 3

More JavaScript examples at level 5

← JavaScript typing practice