1

For this example:

export class DummyClass{  
  constructor(container) {
    const wrapper: HTMLElement = document.createElement("div");
    wrapper.innerHTML = 'x';

    container.append(wrapper);
  }
}

new DummyClass(document.querySelector('body'));

After creating a new instance of DummyClass, is the "wrapper" variable deleted and the memory freed?

Georgian Stan
  • 1,865
  • 3
  • 13
  • 27

2 Answers2

1

Yes, it happens because of how JS works:

When a function returns/end its computation, its memory block is removed from the callstack.

A small example:

 var a;
 function myF(){
    // do stuff
 }();

Before the function call, the call stack will look like this:

-------
|  A  |
-------

Then when function is called:

-------
| myF |
-------
|  A  |
-------

And when the function execution is over:

-------
|  A  |
-------

No trace of any local variable is left in the callstack.

You can find more info in this article

Greedo
  • 3,438
  • 1
  • 13
  • 28
1
const wrapper: HTMLElement = document.createElement("div");

The <div> created by this will continue to be in memory for as long there's some way to reach it from the root of memory. Once the constructor finishes running, the wrapper variable gets cleaned up, so that's one less way the div could be referenced.

However, that's not the only thing that's referencing the div. You've appended the div to the body element, so the body is now going to have a reference to it as one of its children. While that situation continues, the div cannot be garbage collected (and you wouldn't want it to, since it's visible to the user).

Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98