DNB5brims
DNB5brims

Reputation: 30588

JavaScript garbage collection when variable goes out of scope

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?

Upvotes: 5

Views: 4803

Answers (5)

kdgregory
kdgregory

Reputation: 39606

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

Upvotes: 4

James Black
James Black

Reputation: 41858

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

Upvotes: 1

Rakesh Juyal
Rakesh Juyal

Reputation: 36759

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

Upvotes: 1

jldupont
jldupont

Reputation: 96746

Ignore it - after the sayHello function completes, myName falls out-of-scope and gets gc'ed.

Upvotes: 5

Kobi
Kobi

Reputation: 138037

no.
delete is used to remove properties from objects, not for memory management.

Upvotes: 7

Related Questions