The correct way to delete an object and its referring objects in javascript .

Let’s create an object

let obj1 = {
name : "Stark",
age : 23
}

Create another variable with the value referring to the obj1

let obj2 = obj1;

Now we know that whatever operation we do on obj1 alters the value in obj2 and vice versa.

obj1.job = "superhero";
obj1    // {name: "Stark", age: 23, job: "superhero"}
obj2   // {name: "Stark", age: 23, job: "superhero"}
obj2.wife = "Pepper"
obj1  // {name: "Stark", age: 23, job: "superhero", wife : "Pepper"}
obj2  // {name: "Stark", age: 23, job: "superhero" wife : "Pepper"}

When we want to empty the object what we do is obj1 = {};

In this case obj1 is pointing to new objectΒ , but the old object is not deletedΒ .so when you refer obj2Β , it prints the old value

obj1 // {}
obj2 // {name: "Stark", age: 23, job: "superhero" wife : "Pepper"}

In other wordΒ ..

When we use obj = {}Β ,it only changes the reference points toΒ , it doesn’t deletes the object because, If it deletes the object itself, then the other object referring to that object will be affected.

So If we want to delete an object and its referring object at the same time.

function delteObject(obj) {
   Object.keys(obj).
forEach(key => delete obj[key]);
 }

Bye πŸ‘‹πŸ½ πŸ‘‹πŸ½ πŸ‘‹πŸ½ πŸ‘‹πŸ½ πŸ‘‹πŸ½ πŸ‘‹πŸ½ πŸ‘‹πŸ½πŸ‘‹πŸ½πŸ‘‹πŸ½πŸ‘‹πŸ½πŸ‘‹πŸ½πŸ‘‹πŸ½πŸ‘‹πŸ½πŸ‘‹πŸ½πŸ‘‹πŸ½πŸ‘‹πŸ½πŸ‘‹πŸ½

Leave a comment

Design a site like this with WordPress.com
Get started