Garbage collection in Javascript is a nebulous thing. Generally speaking, you can assume (though we know what assuming does) that once there are no references to a variable (eg, once it goes out of scope), it will be garbage collected. However, your closures will not work as you intend because they are not assigned to anything; thus you will have no function object to call getx()
on. If you were to assign it, though, x
would never be out of scope unless you used the delete
keyword on any variables holding the function reference.
Simple rule: use the delete
operator whenever you're concerned about collection - this will remove the reference, and it's more likely that the memory will be freed.
Edit: comments by @chuckj aside, whether you use delete
or assign the variable to undefined
still lends to the point that you want to get the reference count to 0 if there's to be any hope of freeing the memory.