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.
How to Deep Freeze an Object in JavaScript
To deep freeze an object in JavaScript, follow these steps:
- Use
Object.keys()to get all the properties of the passed object. - Iterate over the properties using
Array.prototype.forEach(). - Call
Object.freeze()recursively on all properties that are objects, applyingdeepFreeze()as necessary. - 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.