Javascript closures and memory

Hi, Closures allow a function to access data that is outside of its local scope. Closures are now everywhere in most complex web applications. Bu there is however a performance impact associating with using closures.

Let’s see this code:

// Function that assign an "onClick" event
function assignEvents() {
    let id = '1234';
    let button = document.getElementById("save-button");
     // Closure
    // Assigning onClick event to a button
    button.onClick = function(event) { // This function will be executed when onClick happen
        saveDocument(id); // Other function

In order for this closure to access id, a specific scope chain must be created.

When the function assignEvents() is executed, an activation object is created that contains, among other things, the id variable. This become the first object in the execution context’s scope chain, with the global object coming second. When the closure is created, its “Scope” property is initialized with both of these objects (activation object and global object).

Typically, Activation object is destroyed when the execution context is destroyed. But when there’s a closure involved, though, the activation object isn’t destroyed because a reference exist in the closure’s scope property.

This means that the closures require more memory overhead in a script than nonclosure functions, closures can cause memory leaks in large applications.

An advice for this will be store any frequently used out-of-scope variables in local variables, and then access the local variables directly.

Source: High Performance JavaScript 

By Cristina Rojas.