If the variable persists (e.g. it's global or part of some persistent data structure) and the data it points to is large and you want that data to be eligible for garbage collection, then you are correct to assign something small to that variable. undefined
or null
or ""
will all work. What you're doing is clearing the reference to the large data so that it will be eligible for garbage collection. If nothing else in your javascript has a reference to that data, then it can be freed by the garbage collector. If anything else has a reference to it, then it cannot be freed.
For example, if you had a 10,000 element array held in a global variable:
var largeDataArray = new Array(10000);
And, you had filled most elements with data, then you could allow that memory to be eligible for garbage collection by assigning it some other value like:
largeDataArray = null;
or if you still want it to be an array:
largeDataArray = [];
Note: variables that themselves go out of scope (like local variables in functions that aren't part of a lasting closure) or variables in objects that themselves go out of scope do not have to be manually cleared. When they go out of scope or when the parent object is deleted, the data contained within will also be eligible for garbage collection.
So, the clearing of a variable only needs to be done when you explicitly want to free data that is held in a long lasting variable and it's usually only relevant to worry about this when the data is large or you have a lot of them that add up to multiple megabytes of data (memory use is of higher concern at lower levels on smartphones than in desktop browsers).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…