JavaScript

Shallow freeze vs Deep freeze in JavaScript

In JavaScript, the shallow freeze and deep freeze approaches make an object immutable/non-modifiable. But why should someone use shallow freeze or deep freeze? Well! In JavaScript, everything is an object, and we all know that the objects in JavaScript are mutable(modifiable). But what if someone wants to make objects immutable(non-modifiable)?

There are multiple ways to make an object immutable, such as using the “const” keyword, shallow freeze, and deep freeze.

This write-up aims to present a clear understanding of the following concepts:

  • What is the need for shallow freeze?
  • What does shallow freeze mean in JavaScript?
  • What is the need for deep freeze in JavaScript?
  • What does deep freeze mean in JavaScript?
  • Practical implementation of the deep freeze in JavaScript.

We will understand each of the concepts mentioned above through practical examples. So, let’s get started!

What is the need for a shallow freeze?

The below-listed reasons compel us to implement the shallow freeze or deep freeze:

  • Everything revolves around the objects in JavaScript.
  • Objects in javascript are mutable(modifiable).
  • One way to make an object immutable is using the “const” keyword.
  • An object declared with the “const” keyword can not be modified/reassigned. However, its properties can be modified/reassigned.
  • So, what if someone wants to lock/freeze an object completely?
  • Well! The concept of shallow freeze can be used in such cases.

Example: Problem Identification

This program will identify why the “const” keyword is not a good approach for making objects immutable.

const empDetails = { first: "Alex", second: "John", third: "Mike", fourth: "Joe", fifth: "Seth" };
console.log("Original Object values: ", empDetails);
empDetails.third = "Ambrose";
console.log("Modified Object values: ", empDetails);
  • Firstly, we created an object using “const” keyword and assigned it some key-value pairs.
  • Next, we printed the original values of the object.
  • Afterward, we modified the value of the “third” key.
  • Finally, we printed the modified object values using the “console.log()”.

The output verified that the “const” keyword failed to prevent an object from being modified. The shallow freeze approach can be used to resolve/fix this problem.

What does shallow freeze mean in JavaScript?

The Object.freeze() method can completely freeze an object. The Object.freeze() method restricts a user from adding, deleting, or modifying the object. Moreover, It restricts the users from accessing an object’s existing methods/properties.

Example: Implementation of Object.freeze() method
Let’s consider the below-given code to get a basic understanding of the Object.freeze() method:

const empDetails = {first: "Alex", second: "John", third: "Mike", fourth: "Joe", fifth: "Seth"};
console.log("Original Object values: ", empDetails);
Object.freeze(empDetails);
empDetails.third = "Ambrose";
delete empDetails;
 console.log("Modified Object values: ", empDetails);
  • We used the Object.freeze() method to freeze the “empDetails” object.
  • Next, we printed the original values of the object “empDetails”.
  • Afterward, we tried to update the “third” property of the “empDetails” object..
  • Next, we utilized the delete operator to delete the “third” property.
  • Finally, we printed both the “Modified object values” using the console.log() method.

The output clarified that the Object.freeze() method doesn’t allow modifications to the object.

What is the need for the deep freeze in JavaScript?

The above example shows that the shallow freeze approach successfully prevents the object from modifying. Still, it is not considered the best approach. This is because the shallow freeze approach only freezes the given object. However, if the object contains some nested objects or arrays, then in such situations, the nested objects can still be updated.

So, How to deal with nested objects? Well! In such a case, we can use the concept of the deep freeze.

What does deep freeze mean in JavaScript?

You must follow the below-listed steps to apply the deep freeze to an object:

  • We have to freeze every property recursively.
  • To do that, firstly, check whether the value of any property is an object or not.
  • If the value of any property is an object, then check if it’s frozen.
  • If the value of any property is an object and still it’s not frozen, then invoke the freeze method on that property recursively.
  • In this way, you can create an immutable object.

Practical implementation of the deep freeze in JavaScript

The below-given program will let you understand how to deep freeze an object in JavaScript:

const empDetails = {
  first: "Alex",
  second: "John",
  third: "Mike",
  fourth: ["Joe", "Dean"],
  fifth: "Seth"
};
const deepF = (empDetails) => {
    Object.keys(empDetails).forEach((objProp) => {
      if (
        typeof empDetails[objProp] === "object" &&
        !Object.isFrozen(empDetails[objProp])
      )
        deepF(empDetails[objProp]);
    });
    return Object.freeze(empDetails);
  };  
deepF(empDetails);

console.log("Original Object values: ", empDetails);
  Object.freeze(empDetails);
  empDetails.fourth[0] = "Ambrose";
  console.log("Modified Object values: ", empDetails);

In this program, we adopted the recursive approach to freeze every object’s property. To do so, initially, we checked whether the value of any property is an object or not. When we found that a property is an object, then we checked whether it’s frozen or not. If the value of any property is an object and still it’s not frozen, then we invoke the Object.freeze() method on that property recursively.

From the above-given output, it is clear that the deep freeze approach prevents the object from being modified.

Conclusion

In JavaScript, the shallow freeze and deep freeze approaches make an object immutable/non-modifiable. The difference between shallow freeze and deep freeze is that the shallow freeze doesn’t deal with the nested objects/arrays. On the other hand, the deep freeze approach can be used to freeze an object completely including the nested objects/arrays. This write-up explained the working of shallow freeze and deep freeze with the help of suitable examples.

About the author

Anees Asghar

I am a self-motivated IT professional having more than one year of industry experience in technical writing. I am passionate about writing on the topics related to web development.