Back

Technologies:

javascriptjavascript
avatar
Tolerim
6 hours ago

What are the topics related to JS that cover browser, DOM elements, and garbage collection?

As a senior JavaScript developer, I am exploring the concept of memory leaks in JavaScript, and I stumbled upon an interesting example. In this code snippet, a "nodes" object is created, which has an "owner" property that references a DIV element node obtained using the getElementById() method. Later in the code, the element is removed using the remove() method. However, I understand that the object still holds a reference to the element, and hence the element can not be garbage collected.

let nodes = {
    owner: document.getElementById('owner')
};
document.getElementById('owner').remove();
I am trying to visualize how this works and to understand the relationship between the browser/DOM and the JavaScript running within it. In my understanding, a DOM node is a special object that is stored in the memory heap. Does the browser/DOM hold references to these objects in the heap? Does the JavaScript code running within the browser also have references to these objects? Do they share memory addresses when dealing with global functions and DOM objects, or is my understanding flawed?

Here is my visualization:

enter image description here

Answers(1)
avatar
Tolerim
6 hours ago
Verified Answer
Yes, your understanding is correct. The DOM node is represented as an object in memory and the "nodes" JS object's "owner" property has a reference/pointer to it. The browser's DOM retains a reference to the node because it is still in the page, even though it has been removed from the DOM tree. The JavaScript running in the browser also retains a reference to the node because the "nodes" object still has a reference to it. Your visualization is a good representation of the relationships between the various objects in memory. However, it's worth noting that the exact details of how memory is managed can vary between browsers and JavaScript engines. In general, though, the browser and JavaScript running within it do share memory when dealing with DOM objects and global functions.
;