The correct way to delete an object and itโs 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 ๐๐ฝ ๐๐ฝ ๐๐ฝ ๐๐ฝ ๐๐ฝ ๐๐ฝ ๐๐ฝ๐๐ฝ๐๐ฝ๐๐ฝ๐๐ฝ๐๐ฝ๐๐ฝ๐๐ฝ๐๐ฝ๐๐ฝ๐๐ฝ