Closures in javascript


Hi everyone my name is Himanshu Pandey and this article is related closures in javascript. Closures are one of the most powerful aspects of JavaScript, allowing a function to access data that is outside of its local scope. It has been heavily popularized through Douglas Crockford.

Background

Closures are a concept when child function defined inside parent function and child function access the variable that defined in parent function.

Closures has access the variables in three scope
  • Variables declared in global scope
  • Variables declared in parent scope
  • Variable declared in local scope

var globalScopeVar = "dotnetfunda.com"; 

// Self invoking function for parent or IIFE
(function outerScopeFunction (outerScopeArg) { // begin of scope outerFunction
    // Variable declared in outerScopeFunction function scope 
    var outerScopeFuncVar = 'x';    
    // Closure self-invoking  function or IIFE
    (function innerScopeFunction (innerScopeArg) { // begin of scope innerScopeFunction
        // variable declared in innerScopeFunction function scope
        var innerScopeFuncVar = "y"; 
        console.log(          
            "outerScopeArg = " + outerScopeArg + "\n" +
            "outerFuncVar = " + outerScopeFuncVar + "\n" +
            "innerScopeArg = " + innerScopeArg + "\n" +
            "innerScopeFuncVar = " + innerScopeFuncVar + "\n" +
            "globalScopeVar = " + globalScopeVar);

    })(5); // Pass 12 as parameter 
})(7); // Pass 8 as parameter 
//Output of above code is
outerScopeArg = 7
outerFuncVar = x
innerScopeArg = 5
innerScopeFuncVar = y
globalScopeVar = dotnetfunda.com

Conclusion

Advantage of Closures 

  • Data encapsulation or bind the variables to its execution context.
  • Is useful in the callback or events, just define the closures on click button but this closures reference the variables declared on caller scope.

Disadvantage of Closures

 
A performance impact associated with using closures
  • When there’s a closure involved, though, the activation object isn’t destroyed, because a reference still exists.This means that closures require more memory overhead in a script than a nonclosure function. In large web applications, this might become a problem, especially where Internet Explorer is concerned. IE implements DOM objects as nonnative JavaScript objects, and as such, closures can cause memory leaks.