Deep Freeze Object

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore how to deep freeze an object in JavaScript. We will learn how to use the Object.freeze() method recursively to freeze all properties of an object, making it immutable. By the end of this lab, you will have a better understanding of how to prevent modifications to objects and ensure data integrity in your JavaScript code.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic 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/cond_stmts("`Conditional Statements`") javascript/BasicConceptsGroup -.-> javascript/array_methods("`Array Methods`") subgraph Lab Skills javascript/variables -.-> lab-28263{{"`Deep Freeze Object`"}} javascript/data_types -.-> lab-28263{{"`Deep Freeze Object`"}} javascript/arith_ops -.-> lab-28263{{"`Deep Freeze Object`"}} javascript/comp_ops -.-> lab-28263{{"`Deep Freeze Object`"}} javascript/cond_stmts -.-> lab-28263{{"`Deep Freeze Object`"}} javascript/array_methods -.-> lab-28263{{"`Deep Freeze Object`"}} end

How to Deep Freeze an Object in JavaScript

To deep freeze an object in JavaScript, follow these steps:

  1. Use Object.keys() to get all the properties of the passed object.
  2. Iterate over the properties using Array.prototype.forEach().
  3. Call Object.freeze() recursively on all properties that are objects, applying deepFreeze() as necessary.
  4. Finally, use Object.freeze() to freeze the given object.

Here's the code:

const deepFreeze = (obj) => {
  Object.keys(obj).forEach((prop) => {
    if (typeof obj[prop] === "object") deepFreeze(obj[prop]);
  });
  return Object.freeze(obj);
};

You can test the deep frozen object using the following code:

"use strict";

const val = deepFreeze([1, [2, 3]]);

val[0] = 3; // not allowed
val[1][0] = 4; // not allowed as well

The above code will throw an error because the val object is deeply frozen and cannot be modified.

Summary

Congratulations! You have completed the Deep Freeze Object lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like