Is it possible to make a nested object immutable using Object.freeze() in JavaScript?

JavascriptObject Oriented ProgrammingFront End Technology

Object.freeze() method can make an object immutable but in case of a nested object, it can't prevent mutability. Object.freeze() can only provide immutability to the outside parent object, it can't access any inner child(nested) objects.

Example

In the following example, there are no nested objects. Object.freeze() method will try to freeze the whole object. Therefore there is no change in the property "name" even after freezing the object.

Live Demo

<html>
<body>
   <script>
      const person = {
         "name" : "Suresh",
         "Country" : "India",
         "Designation" : "Mayor"
      }
      document.write("Before freeze the name is" +" "+ person.name );
      document.write("</br>");
      Object.freeze(person);
      person.name = "John";
      document.write("After freeze the name is" +" "+ person.name);
   </script>
</body>
</html>

Output

Before freeze the name is Suresh
After freeze the name is Suresh

When a nested object is tried to frozen by Object.freeze() the result is in vain because Object.freeze() can't access nested objects. 

Example

In the following example, even though the object is frozen by Object.freeze() method the property of a nested object is changed. 

Live Demo

<html>
<body>
<script>
   const person = {
      "name" : "Suresh",
      "Country" : "India",
      "Designation" : "Mayor",
      "CompaniesOwned" :{
         "Company1" : "Tesla",
         "Company2" : "SolarCity",
         "Company3" : "Spacex"
      }
   }
   document.write("Before freeze " + " " + "Company2 is" + " "+ person.CompaniesOwned.Company2);
   Object.freeze(person);
   document.write("</br>");
   person.CompaniesOwned.Company2 = "Neuralica";
   document.write("After freeze" + " " + "Company2 is" + " "+ person.CompaniesOwned.Company2);
</script>
</body>
</html>

Output

Before freeze Company2 is SolarCity
After freeze Company2 is Neuralica
raja
Published on 28-Jun-2019 15:29:41
Advertisements