Deep freeze is a great module from the prolific Substack. Before we get into how it works, let’s talk about what it is.

According to the readme, deep freeze is used to:

recursively Object.freeze() objects

Object.freeze is a built in JavaScript method that allows you to “freeze” an object. According to the docs that means:

It prevents new properties from being added to it; prevents existing properties from being removed; and prevents existing properties, or their enumerability, configurability, or writability, from being changed.

Let’s take a look at what this means.

As most of you probably know, you can set new properties on an object or change the existing properties at any time. This is what Object.freeze() prevents. Check out the following example:

Now we can see that with Object.freeze you can no longer change or add properties. However, Objects that are frozen aren’t quite immutable. Let’s see another example:

This is where Deep Freeze comes in! It will freeze your object and any objects declared as properties recursively down the three of your object.

The Code

Let’s walk through it line by line!

  1. Module exports for Node.js imports
  2. Take in the first object ( named “o” ) and freeze it
  3. A blank line!
  4. Get each property on the object and iterate through them
  5. If the property belongs to the object ( not the prototype )
  6. Also if the property is not null
  7. Also if the property is “object” type or “function” type
  8. And lastly, if the property isn’t already frozen
  9. Then, run deep freeze on it and all of its properties