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 objects1function deepFreeze(obj) { // Object.freeze prevents modification of the object's properties2 Object.freeze(obj); // Iterate through all property keys3 for (const key of Object.keys(obj)) { // Get the property value4 const val = obj[key]; // Check if value is a non-null object that isn't already frozen5 if (val !== null && typeof val === "object" && !Object.isFrozen(val)) { // Recursively freeze nested objects6 deepFreeze(val);7 }8 } // Return the frozen object for chaining9 return obj;10}11 // Create and deeply freeze a config object12const config = deepFreeze({ // Nested object that will also be frozen13 api: { url: "https://api.example.com" },14 timeout: 500015});16 // Access the nested URL17console.log(config.api.url);// Verify the nested object is frozen18console.log(Object.isFrozen(config.api));Output
https://api.example.com 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)× 11;× 7=× 7{× 5}× 5:× 4"× 4&× 4