JavaScript(JS) object method - isFrozen
The isFrozen()
method is a built-in method of the JavaScript Object
constructor. It returns a boolean indicating whether the specified object is frozen, i.e., whether its properties are read-only and cannot be changed.
Here's the syntax:
Object.isFrozen(obj)Source:www.theitroad.com
where obj
is the object to be checked. This method takes only one argument, which is the object to be checked.
Here's an example that shows how to use the isFrozen()
method:
const myObj = { prop1: "value1", prop2: "value2" }; console.log(Object.isFrozen(myObj)); // false Object.freeze(myObj); console.log(Object.isFrozen(myObj)); // true myObj.prop1 = "new value"; console.log(myObj.prop1); // "value1"
In this example, we create an object myObj
with two properties prop1
and prop2
. We use the isFrozen()
method to check whether the object is frozen. Since the object is not frozen yet, isFrozen()
returns false
.
Next, we use the Object.freeze()
method to make the object read-only. We then use the isFrozen()
method again to check whether the object is frozen. Since we have frozen the object, isFrozen()
now returns true
.
Finally, we try to modify the prop1
property of the object, but it remains unchanged since the object is frozen. When we log the value of myObj.prop1
, we see that it is still "value1"
.
The isFrozen()
method is useful for checking whether an object is read-only or not. If an object is frozen, you cannot add, modify, or delete its properties.