Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
October 8, 2021 11:03 am GMT

Deep Freeze tutorial for Beginners by a Beginner

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 -> Hritickobj.name = "Hritick Jaiswal";console.log(obj.name);//* Prints -> Hritick Jaiswal

But now if we use Object.freeze

Object.freeze(obj); //* Freezes the objectconsole.log(Object.isFrozen(obj)); //* Checks if an object is frozen or notobj.name = "Hritick"; //* Changing values is ignoredconsole.log(obj);//* Prints -> { name: 'Hritick Jaiswal' }obj.surname = "Jaiswal"; //* Adding values is ignoredconsole.log(obj);//* Prints -> { name: 'Hritick Jaiswal' }delete obj.name; //* Deleting values is ignoredconsole.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 -> KolkataObject.freeze(obj)obj.address.is = "Hyderabad"; //! This is allowedconsole.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


Original Link: https://dev.to/newbiehritick/deep-freeze-tutorial-for-beginners-by-a-beginner-1glf

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To