Are there rules or best practices to write JavaScript code that is not memory hungry?
Back in time when I had to allocate and deallocate each byte in my software, I had a good picture of memory usage in my mind. But now I am alsways uncertain. All those cross and circular references, closures, duck typing, I got used to those great features but always feel uncertain about the memory effectivnes.
Well, knowing how your car works and how it is designed is one thing, but having a good set of practical rules how not to kill it too fast is another thing.
Are you referring to client-side JS (browser related) or server side (node.js)? While some fundamentals might be the same, I believe the actual answer will be quite different depending on this.
Anytime you exit a scope, the garbage collector does its job. So if you move some code to a function that executes and ends, all of the variables will be garbage collected when the function is over (except for the ones that were available before the function was called in the first place).
What about objects in function scope that are also closed over? The statement "executes and ends, all of the variables will be garbage collected when the function is over" is incorrect.
No. That's just not how it works. The garbage collection algorithms used by browsers take varying routes, but none of them go for "function ended, garbage collect". Closures are a fundamental part of Javascript and GCing function scoped variables at function end time would decimate this concept.