Problem with Object in JavaScript
We all know that JavaScript objects are mutable. How can we make them immutable? Define them as const but if we declare a JavaScript object as a const, it only prevents the object from getting reassigned as a whole. We can still reassign the properties and change their value.
Example 1:
const obj1 = { key1: "val1", key2: "val2", key3: "val3" };
console.log("Before Change");
console.log(obj1);
obj1.key1 = "val";
console.log("After Change");
console.log(obj1);
Output:
"Before Change"
{
key1: "val1",
key2: "val2",
key3: "val3"
}
"After Change"
{
key1: "val",
key2: "val2",
key3: "val3"
}
There are several methods that can be used to deep-freeze an object.
- Using Object.freeze()
- Using JSON.parse() and JSON.stringify()
- using Object.freeze() and Object.isFrozen()
We will explore all the above methods along with their basic implementation with the help of examples.
How to deep-freeze an object in JavaScript ?
In this article, we will see what is the problem with objects in JavaScript and why we need to “deep-freeze” an object in JavaScript. We will also learn how to “deep-freeze” an object in JavaScript.