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 function1function deepFreeze(obj) { // Iterate over all keys in the object2 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 object4 deepFreeze(obj[key]);5 }6 }); // Freeze and return the object7 return Object.freeze(obj);8}// Create deeply frozen config object9const config = deepFreeze({ // Nested object that will also be frozen10 api: { url: "https://api.example.com" }, // Primitive property11 debug: true12});// Check if the root object is frozen: true13console.log(Object.isFrozen(config));// Check if the nested object is also frozen: true14console.log(Object.isFrozen(config.api));Output
true true
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