From the point of view of garbage collection, there is no difference between anonymous and named functions:
function dostuff(){
var dog = {};
}
dostuff();
In your particular example, dog
goes out of scope when your function ends. Since nothing else is pointing to that object, it should be garbage collected.
However, if there are inner functions, then some of the variables might be saved inside of closures and not get garbage collected;
function dostuff(){
var dog = {name:"dog"};
var cat = {name:"cat"};
setInterval(function(){
console.log(dog.name);
}, 100);
}
In this case dog is referenced in the callback that you passed to setInterval so this reference gets preserved when dostuff exits and will not be garbage collected. As for the cat
variable it depends on the implementation. Some implementation will notice that cat
is not used in any inner function and will garbage collect its contents. However, some other implementations will save all the variables in scope even if only one of them is used in an inner function.
For more information, see this: How JavaScript closures are garbage collected