Deep Freeze tutorial for Beginners by a Beginner
I got into web development just a few months back and a few days ago I came across a interview question asking to write code to deep freeze an object.
But what is freezing an object ???
Freezing an object means preventing new properties from being added to it, existing properties from being removed, prevents changing the enumerability, configurability, or writability of existing properties. Basically freezing an object means we cannot add ,delete or change existing properties which otherwise would have been possible in javascript as it is a dynamic language.
To freeze objects in javascript we use Object.freeze() method
const obj = {
name: "Hritick",
};
console.log(obj.name); //* Prints -> Hritick
obj.name = "Hritick Jaiswal";
console.log(obj.name);//* Prints -> Hritick Jaiswal
But now if we use Object.freeze
Object.freeze(obj); //* Freezes the object
console.log(Object.isFrozen(obj)); //* Checks if an object is frozen or not
obj.name = "Hritick"; //* Changing values is ignored
console.log(obj);//* Prints -> { name: 'Hritick Jaiswal' }
obj.surname = "Jaiswal"; //* Adding values is ignored
console.log(obj);//* Prints -> { name: 'Hritick Jaiswal' }
delete obj.name; //* Deleting values is ignored
console.log(obj);//* Prints -> { name: 'Hritick Jaiswal' }
Ok great but what the hell is deep freeze and if we have Object.freeze and why do we need it.
const obj = {
name: "Hritick",
address: {
is: "Kolkata",
},
};
console.log(obj.address.is);//* Prints -> Kolkata
Object.freeze(obj)
obj.address.is = "Hyderabad"; //! This is allowed
console.log(obj.address.is);//* Prints -> Hyderabad
So why did Object.freeze did not work ???
Well Object.freeze did work
It did "freeze" the properties of the object "obj" as the property "address" stores the memory location of the object { is:"Kolkata" } which cannot be changed but Object.freeze works on the immediate layer only.
Deep freezing is preventing from such cases. So what should we do ....
function deepFreeze(object) {
if (typeof object !== "object") return;
for (const value of Object.values(object)) {
deepFreeze(value);
}
Object.freeze(object);
}
The above code uses recursion to basically freeze every object no matter at what level it is.
And that's it , this is my first post here so if I made any mistakes or anyone has any suggestions please tell me
Top comments (0)