Does javascript garbage collector collect global variables?

I am confused by this since I saw several different comments. I read a javascript book that mentions setting global variables to zero is good practice (assuming there are no other references), and GC restores memory for this variable in the next step. I saw other comments that say that global variables are never deleted by the GC.

Also when programming javascript in the OOP framework, what happens if I have something like this (where the game is in a global context):

var game = {}; game.level = 0; game.hero = new hero(); //do stuff game.hero = null; 

Since the hero lives inside an object that is stored in a game that is in a global context, if I set the hero, for example, to null, will it be selected by GC?

+8
javascript garbage-collection
source share
1 answer

Global variables are never deleted by the GC in the sense that the global variable will still exist. However, setting null will allow the memory that it refers to the collection.

eg.

Before:

 global -> {nothingness} 

After:

 global -> var a -> object { foo: "bar" } 

Set a to null :

 global -> var a -> null 

Here, the memory used by the object will have the right to collect. The variable a still exists, and it just refers to null .

The assertion that global variables are never collected is a bit misleading. Perhaps it would be more accurate to say that any memory that is tracked back to the global context is currently not eligible for collection.

In answer to your question, yes - the hero object will have the right to collect, because its indirect connection with the global context has been broken.

+14
source share

All Articles