JavaScript Development Space

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 object
3 const propNames = Object.getOwnPropertyNames(obj);
4
5 // Freeze properties before freezing the object itself
6 for (let name of propNames) {
7 let prop = obj[name];
8
9 // If the property is an object, freeze it recursively
10 if (typeof prop === 'object' && prop !== null) {
11 deepFreeze(prop);
12 }
13 }
14
15 // 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 };
9
10 // Deep freeze the person object
11 deepFreeze(person);
12
13 // Trying to modify properties
14 person.name = 'Jane'; // Won't work
15 person.address.city = 'Los Angeles'; // Won't work
16 person.hobbies.push('cycling'); // Won't work
17
18 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.

JavaScript Development Space

© 2024 JavaScript Development Space - Master JS and NodeJS. All rights reserved.