/

The Object.freeze() Method: A Deep Dive

The Object.freeze() Method: A Deep Dive

In JavaScript, the freeze() method of the Object object plays a vital role. This method takes an object as an argument and returns the same object with a significant change. The object passed as an argument becomes immutable - meaning that no properties can be added, removed, or modified.

Let’s take a look at an example:

1
2
3
4
5
6
7
8
9
const dog = {}
dog.breed = 'Siberian Husky'
const myDog = Object.freeze(dog)

Object.isFrozen(dog) // true
Object.isFrozen(myDog) // true
dog === myDog // true

dog.name = 'Roger' // TypeError: Cannot add property name, object is not extensible

In this example, both dog and myDog are frozen. The object passed as an argument to Object.freeze() undergoes mutation and cannot be unfrozen. Additionally, since the same object is returned, dog === myDog evaluates to true.

It is interesting to note that calling Object.freeze() is equivalent to calling Object.preventExtensions() to prevent the object from having additional properties defined. Furthermore, it sets all the properties as non-configurable and non-writable.

To learn more about immutability in JavaScript, you can also refer to the Object.isFrozen() method.

tags: [“JavaScript”, “Object.freeze()”]