-1

I have a function like this

function runThis(){ var class = new aClass(); // using the class variable }

if i run this function several times, can this cause a memory leak or that new class automatically destroyed?

Crytalenz
  • 3
  • 1
  • 3
  • 3
    No leaks, the new class is destroyed after the function has been executed, provided you're not returning any reference to the object outside of the function. – Teemu Apr 07 '20 at 07:37
  • See https://stackoverflow.com/questions/4869712/new-without-delete-on-same-variable-in-javascript – QuentinUK Apr 07 '20 at 07:47

1 Answers1

1

The new class gets destroyed when you go out of the scope (out of runThis in this case) or when you re-assign the variable. The memory gets cleaned only when a new cycle of the garbage collector is ran, like in Java. To learn more about garbage collection you can read here.

This is not much different than Java or other high-level programming languages, but it still presents some caveats. Note that var preserves the variable hoisting. Maybe you'd prefer using const or let.