JavaScript

Closure is one of the trickiest concept of functional programming and all languages that have “first-class functions” support closures.

Closure by literal definition is “The act of closing” or “The state of being closed”

Have a look at function below:


function OuterFunction(outerVariable)
{
var InnerFunction= function(innerVariable)
{
alert('I still remember Outer Variable : '+outerVariable +' when you passed Inner Variable : '+innerVariable);
}
return InnerFunction;
}

var returnFunction = OuterFunction('Yahoo!');

Now when we make a call to returnFunctions(‘bing’); output will be

ClosureAlert

Even though ‘OuterFunction’ has executed and returned ‘InnerFunction’ the value of ‘outerVariable’ is still there in the memory.

‘returnFunction’ will always contain the value of ‘outerVariable’ as ‘Yahoo!’ and it is a closure over the ‘outerVariable’.

2 responses to “Confusing Closures made Simple”

  1. zoom2me Avatar

    Very nicely done

    Like

  2. zoom2me Avatar

    Can we look at it like the following…

    The outerfunction works as a factory. i.e when you first pass the parameter to the outer function then this prepares the inner function and returns it back.

    Lets take your example :

    when the following like is executed
    var returnFunction = OuterFunction(‘Yahoo!’);

    a function like the following is stored in the returnFunction

    
    function InnerFunction(innerVariable)
    {
     
    alert('I still remember Outer Variable : Yahoo! when you passed Inner Variable : '+innerVariable);
     
    }
    

    Now, when InnerFunction is called it works like any other function.

    Like

Leave a comment

I’m Abhinav

Welcome to my Blog. I am a passionate architect and developer dedicated to creating innovative and user-friendly digital experiences. With a background in both design and development, I bring a unique blend of creativity and technical expertise to every project I undertake.

In addition to my technical skills, I have a keen interest in the latest industry trends and enjoy sharing my knowledge through blogging and speaking engagements. When I’m not coding or designing, you can find me exploring new technologies, reading about the latest in tech, or indulging in my love for music and travel.

Let’s connect