Introduction
In this lab, we will learn how to check if an object is deeply frozen in JavaScript. The lab will guide us through a recursive function that uses Object.isFrozen() to determine if an object is frozen and Object.keys() with Array.prototype.every() to check all keys for deep freezing. By the end of this lab, we will have a better understanding of how to determine the deep freezing status of an object in JavaScript.
How to Check if an Object is Deeply Frozen
To check if an object is deeply frozen, use the following steps in JavaScript:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use recursion to check if all the properties of the object are deeply frozen.
- Use
Object.isFrozen()on the given object to check if it is shallowly frozen. - Use
Object.keys()to get all the properties of the object andArray.prototype.every()to check that all keys are either deeply frozen objects or non-object values.
Here's an example code snippet to check if an object is deeply frozen:
const isDeepFrozen = (obj) =>
Object.isFrozen(obj) &&
Object.keys(obj).every(
(prop) => typeof obj[prop] !== "object" || isDeepFrozen(obj[prop])
);
You can use the isDeepFrozen function to check if an object is deeply frozen like this:
const x = Object.freeze({ a: 1 });
const y = Object.freeze({ b: { c: 2 } });
isDeepFrozen(x); // true
isDeepFrozen(y); // false
Summary
Congratulations! You have completed the Check if Object Is Deep Frozen lab. You can practice more labs in LabEx to improve your skills.