Confusing Closures made Simple

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:

[sourcecode language=”javascript”]

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!’);

[/sourcecode]

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’.

4 Comments

  1. zoom2me

    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

    [sourcecode language=”javascript”]

    function InnerFunction(innerVariable)
    {

    alert(‘I still remember Outer Variable : Yahoo! when you passed Inner Variable : ‘+innerVariable);

    }
    [/sourcecode]

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

    Reply
  2. zoom2me

    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

    [sourcecode language=”javascript”]

    function InnerFunction(innerVariable)
    {

    alert(‘I still remember Outer Variable : Yahoo! when you passed Inner Variable : ‘+innerVariable);

    }
    [/sourcecode]

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

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *