Check if Object Is Deep Frozen

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/BasicConceptsGroup -.-> javascript/array_methods("`Array Methods`") javascript/AdvancedConceptsGroup -.-> javascript/destr_assign("`Destructuring Assignment`") subgraph Lab Skills javascript/variables -.-> lab-28416{{"`Check if Object Is Deep Frozen`"}} javascript/data_types -.-> lab-28416{{"`Check if Object Is Deep Frozen`"}} javascript/arith_ops -.-> lab-28416{{"`Check if Object Is Deep Frozen`"}} javascript/comp_ops -.-> lab-28416{{"`Check if Object Is Deep Frozen`"}} javascript/array_methods -.-> lab-28416{{"`Check if Object Is Deep Frozen`"}} javascript/destr_assign -.-> lab-28416{{"`Check if Object Is Deep Frozen`"}} end

How to Check if an Object is Deeply Frozen

To check if an object is deeply frozen, use the following steps in JavaScript:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use recursion to check if all the properties of the object are deeply frozen.
  3. Use Object.isFrozen() on the given object to check if it is shallowly frozen.
  4. Use Object.keys() to get all the properties of the object and Array.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.

Other JavaScript Tutorials you may like