JavaScript garbage collection when a variable goes beyond

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 variable myName or am I just ignoring it?

+4
source share
5 answers

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

+3
source

not.
delete used to delete object properties, not memory management.

+5
source

JavaScript supports garbage collection. In this case, since you explicitly declare the variable inside the function, it will (1) go out of scope when the function exits and will be assembled sometime after that, and (2) cannot be the target of delete (for each link below).

Where delete can be useful if you declare variables implicitly, which puts them in a global scope:

 function foo() { x = "foo"; /* x is in global scope */ delete x; } 

However, it is bad practice to define variables implicitly, so always use var and you won’t have to worry about delete .

For more information see https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/delete_Operator

+4
source

You do not need to do anything Ted, there is no need to delete this variable.

Refer: http://www.codingforums.com/archive/index.php/t-157637.html

+1
source

As already mentioned, when a function exits, your variable goes out of scope, since the scope is only inside the function, so gc can clear it.

But it is possible that this variable can be referenced by something outside the function, then it will not be displayed for some time, if at all, since it still has a link to it.

You might want to read the review in javascript: http://www.webdotdev.com/nvd/content/view/1340/

With closure, you can create a memory leak, which may be the problem you are trying to deal with, and is related to the problem I was talking about: http://www.jibbering.com/faq/faq_notes/closures.html

+1
source

All Articles