-2

Note: object contains other references, so cannot do as described in duplicate.

Let's say I have a large object, such as described in How to delete an object in JavaScript?. If we have the following object then:

s = Set;
s.add(otherSet); // we also have other references to these elements
s.add(otherObject);
// ...
deleteObjectAndAllReferences(s);

How would the function be structured such that it deletes the object and any references that it contains, recursively. I would guess it starts out as, but I think the 'delete' method/operator isn't always the same between different object types.

function deleteObjectAndAllReferences(obj) {
   // do we only need to grab enumerable properties, or all?
    for (elem of obj)                                             
        (typeof elem === 'object')? deleteObjectAndAllReferences(elem) : obj.remove(s);
}
David542
  • 101,766
  • 154
  • 423
  • 727
  • 3
    You cannot "delete" an object in JS, you can only make it garbage-collectable. `s = null` will do that, a function call cannot. – Bergi May 09 '22 at 16:11
  • 1
    Could you please explain why are you trying to delete the object recursively? If you wanna remove all the references to the leaves, you can just delete the root, there's no need (that I am aware of) to proceed recursively. If you know any problem, please include it in your question – Cristian Traìna May 09 '22 at 16:12
  • @CristianTraìna what if there are other references though to the leaves elsewhere in the program? – David542 May 09 '22 at 16:12
  • 1
    @David542 If you delete properties out from underneath other references it sounds like a bug waiting to happen - you should probably consider why you still have other references to something you want to delete. – James Thorpe May 09 '22 at 16:14
  • @JamesThorpe it's more an academic exercise tbh but I'd like to see how to accomplish it. – David542 May 09 '22 at 16:16
  • 3
    @David542 [This is not possible](https://stackoverflow.com/q/10826046/1048572). You will need to find those other places in your program code, and make sure they are getting cleaned up properly. – Bergi May 09 '22 at 16:20
  • a memory profiler can highlight what is owning references to what – Daniel A. White May 09 '22 at 16:21
  • 1
    Even after your edits, Bergi's initial comment still applies. `delete` removes a *reference* to a value. The garbage collector is the only thing that will remove the actual value from memory. You're chasing a mirage, I think. – Scott Sauyet May 09 '22 at 16:22

0 Answers0