Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript closures and memory management

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?

like image 671
Abijeet Patro Avatar asked Feb 06 '14 21:02

Abijeet Patro


People also ask

Does JavaScript have memory management?

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.

Where are closures stored in memory?

So. With this in mind, the answer is that variables in a closure are stored in the stack and heap.

What is the advantage of using closures in JavaScript?

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.

What are JavaScript closures?

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.


1 Answers

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.

like image 190
Russell Zahniser Avatar answered Sep 18 '22 13:09

Russell Zahniser