javascriptperformancememory-managementgarbage-collectionglobal-variables

Why doesn't JavaScript's garbage collector clean up global variables?


I've been reading an article about memory management in JavaScript, and it says that the global scope objects don't get cleaned from the memory.

If a global variable is not being referenced anywhere else in your program, shouldn't the garbage collector be able to collect it and dispose of it just like any other object?


Solution

  • To quote MDN:

    Garbage collection is a term used in computer programming to describe the process of finding and deleting objects which are no longer being referenced by other objects.

    Global variables are always referenced (i.e., you can always access them), so they are never eligible for garbage collection.

    You could, in fact, claim that adding a variable to the global scope creates a memory leak, since it can never be collected.