Reputation:
I was reading this post that clarified almost everything about scopes, leaving only this doubt:
If lexical scopes generate a new environment on each run and store their information, in an environment where code runs frequently, you need to declare var_of_scope = null
at the end of the scope to free memory or JavaScript recognizes this automatically if not are there elements that refer to the environment?
Upvotes: 0
Views: 45
Reputation: 187134
No, that is almost never necessary.
Javascript uses garbage collection. When no values in any scope reference a value stored in memory, it is removed during the next run of garbage collector.
In the situation you describe:
function foo() {
let data = "some data here"
// do stuff with data
data = null
}
Setting the null
here is not helpful. It does remove all references the previous value of data
, but since the scope will end when the function ends, all local variables will be discarded along with it anyway.
In fact, this would prevent you from using the const
keyword, which is a very very good thing to use. All your variables should be const
by default, and you should change them to let
only if you really need to assign them after initialization.
This is better:
function foo() {
const data = "some data here"
// do stuff with data
}
In general, you just don't have to worry about this. It's not easy to leak memory in javascript like it is in a language like C. It's possible but as long your following most best practices you'll probably be fine.
Upvotes: 1