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 objects1function deepFreeze(obj) { // Iterate through all properties2 Object.keys(obj).forEach(key => { // If property is an object (and not null), recurse3 if (typeof obj[key] === "object" && obj[key] !== null) {4 deepFreeze(obj[key]);5 }6 }); // Freeze the current object and return it7 return Object.freeze(obj);8}9 // Create a deeply frozen config object10const config = deepFreeze({11 api: { url: "https://api.example.com", timeout: 5000 },12 debug: false13});14 // Read frozen value - works fine15console.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 ignored17config.debug = true;// Values remain unchanged: the original url and false18console.log(config.api.url);19console.log(config.debug);Output
https://api.example.com https://api.example.com false
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