DeepFreeze a nested Object/Array
To deeply freeze a nested object or array in JavaScript, you need to freeze not only the outer object but also any nested objects or arrays. You can achieve this by creating a recursive function that applies Object.freeze() to all levels of the object.
Here’s an example of how to implement deep freezing:
DeepFreeze Function
js
1 function deepFreeze(obj) {2 // Retrieve the property names defined on the object3 const propNames = Object.getOwnPropertyNames(obj);45 // Freeze properties before freezing the object itself6 for (let name of propNames) {7 let prop = obj[name];89 // If the property is an object, freeze it recursively10 if (typeof prop === 'object' && prop !== null) {11 deepFreeze(prop);12 }13 }1415 // Finally, freeze the outer object (non-recursive objects will stop here)16 return Object.freeze(obj);17 }
Usage Example
js
1 const person = {2 name: 'John',3 address: {4 city: 'New York',5 zip: 10001,6 },7 hobbies: ['reading', 'gaming'],8 };910 // Deep freeze the person object11 deepFreeze(person);1213 // Trying to modify properties14 person.name = 'Jane'; // Won't work15 person.address.city = 'Los Angeles'; // Won't work16 person.hobbies.push('cycling'); // Won't work1718 console.log(person);19 // Output: { name: 'John', address: { city: 'New York', zip: 10001 }, hobbies: [ 'reading', 'gaming' ] }
How It Works:
- The deepFreeze() function freezes the object itself, and for each property that is an object (or array), it recursively freezes those as well.
- The function ensures that all levels of the object/array hierarchy are made immutable, preventing any modifications.
This method ensures full immutability for complex objects with nested structures.