/

The Object isFrozen() Method: Explained and Demonstrated

The Object isFrozen() Method: Explained and Demonstrated

The isFrozen() method in JavaScript can be used to determine whether an object is frozen or not. When an object is frozen, it means that it cannot be modified. This method accepts an object as an argument and returns true if the object is frozen, and false otherwise.

Objects are typically frozen using the Object.freeze() function. When an object is frozen, its properties cannot be added, modified, or removed. The isFrozen() method allows you to check the frozen state of an object and make decisions based on that information.

Here’s an example to illustrate how isFrozen() works:

1
2
3
4
5
6
7
8
const dog = {};
dog.breed = 'Siberian Husky';

const myDog = Object.freeze(dog);

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

In this example, both dog and myDog are frozen objects. The Object.freeze() function is used to freeze the dog object, and the resulting frozen object is assigned to myDog. As a result, both dog and myDog are frozen and cannot be modified.

It’s important to note that when an object is frozen, any changes made to the frozen object will have no effect. Additionally, frozen objects cannot be unfrozen or modified in any way. This is why dog and myDog are considered identical (i.e., dog === myDog is true) because they refer to the same exact frozen object.

In conclusion, the isFrozen() method is a valuable tool for checking the frozen state of an object in JavaScript. It allows you to determine whether an object is modifiable or not, providing you with control and decision-making capabilities in your code.

tags: [“JavaScript”, “Object”, “isFrozen”, “Object.freeze”]