Does JavaScript support garbage collection?
For example, if I use:
function sayHello (name){
var myName = name;
alert(myName);
}
do I need to use "delete" to delete the myName
variable or I just ignore it?
Does JavaScript support garbage collection?
For example, if I use:
function sayHello (name){
var myName = name;
alert(myName);
}
do I need to use "delete" to delete the myName
variable or I just ignore it?
- certainly no, CTO: codingforums.com/archive/index.php/t-157637.html – Rakesh Juyal Commented Oct 22, 2009 at 13:44
- Please retag/retitle: this has nothing to do with optimization. I suggest "JavaScript variable scope" – kdgregory Commented Oct 22, 2009 at 13:49
- See also this question about the JS GC - stackoverflow.com/questions/864516/… – Kobi Commented Oct 22, 2009 at 13:51
5 Answers
Reset to default 7no.
delete
is used to remove properties from objects, not for memory management.
Ignore it - after the sayHello function completes, myName falls out-of-scope and gets gc'ed.
JavaScript supports garbage collection. In this case, since you explicitly declare the variable within the function, it will (1) go out of scope when the function exits and be collected sometime after that, and (2) cannot be the target of delete
(per reference linked below).
Where delete
may be useful is if you declare variables implicitly, which puts them in global scope:
function foo()
{
x = "foo"; /* x is in global scope */
delete x;
}
However, it's a bad practice to define variables implicitly, so always use var
and you won't have to care about delete
.
For more information, see: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/delete_Operator
You don't need to do anything Ted, no need to delete this variable.
Refer: http://www.codingforums.com/archive/index.php/t-157637.html
As others mentioned, when the function exits then your variable falls out of scope, as it's scope is just within the function, so the gc can then clean it up.
But, it is possible for that variable to be referenced by something outside the function, then it won't be gc'ed for a while, if ever, as it is still has a reference to it.
You may want to read up on scoping in javascript: http://www.webdotdev.com/nvd/content/view/1340/
With closures you can create memory leaks, which may be the problem you are trying to deal with, and is related to the problem I had mentioned: http://www.jibbering.com/faq/faq_notes/closures.html