I'm curious as to how memory is handled with variables inside closures. Take this code for example -
function iAmAClosure() {
var txtName = document.getElementById('name');
function validation() {
if (txtName.value.length === 0) {
return false;
}
return true;
}
document.getElementById('submit').onclick = function () {
return validation();
}
}
My validation
function is called whenever the user clicks on a button.
My question is, does the txtName
variable stay in memory as long as the page is active, or is it GC'ed and initialized every time the method validation is called? Is there something more to it then that?
What's better performance wise?
Some high-level languages, such as JavaScript, utilize a form of automatic memory management known as garbage collection (GC). The purpose of a garbage collector is to monitor memory allocation and determine when a block of allocated memory is no longer needed and reclaim it.
So. With this in mind, the answer is that variables in a closure are stored in the stack and heap.
Advantages of closures Variables in closures can help you maintain a state that you can use later. They provide data encapsulation. They help remove redundant code. They help maintain modular code.
In JavaScript, a closure is a function that references variables in the outer scope from its inner scope. The closure preserves the outer scope inside its inner scope. To understand the closures, you need to know how the lexical scoping works first.
Any variables in the closure of a function are kept in memory as long as there is a way to reference that function. Here, txtName
is in the closure of your onclick
function, so it will stay in memory as long as the onclick
binding is intact and the "submit" button exists.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With