The Object.isFrozen()
method checks if an object is frozen.
Example
let obj = {name: "JavaScript"};
// new objects are extensible, so they're not frozen
console.log(Object.isFrozen(obj));
// Output: false
isFrozen() syntax
The syntax of the isFrozen()
method is:
Object.isFrozen(obj)
Here, isFrozen()
is a static method. Hence, we need to access the method using the class name, Object
.
Note: A frozen object can no longer be changed. Freezing an object prevents:
- New properties from being added to the object.
- Existing properties to be removed from the object.
- Changing the enumerability, configurability, or writability of existing properties.
- Changing values of the existing object properties and prototype.
isFrozen() Parameters
The isFrozen()
method takes in:
- obj - the object which should be checked for being frozen or not.
isFrozen() Return Value
The isFrozen()
method returns:
true
- if the object is frozenfalse
- if the object is not frozen
Example: Javascript Object.isFrozen()
let newObj = { b: 2 };
// preventing extensions doesn't freeze an object
// since its properties are still configurable
Object.preventExtensions(newObj);
// check if newObj is frozen
console.log(Object.isFrozen(newObj));
// Output: false
// make newObj non-writable
Object.defineProperty(newObj, "b", {
writable: false,
});
// object is not frozen
console.log(Object.isFrozen(newObj));
// Output: false
// use the freeze() method
Object.freeze(newObj);
// object is finally frozen
console.log(Object.isFrozen(newObj));
// Output: true
In the above example, we tried to freeze newObj by
- using the
preventExtensions()
method, and - making it unwritable by setting the
writable
flag tofalse
.
However, both approaches fail to freeze the object.
The final output indicates that newObj is frozen only after calling the freeze()
method.
Recommended Reading: