Javascript Closures

September 16, 2008 at 2:10 pm | Posted in Javascript | Leave a comment

One of the features of Javascript is closures , Javascript closures keep the local variables of a function even after it returns. That happens when a function is declared inside another function ,the local variables of the outer function will still exist even after the outer function returns.

function outer()
var name="mabdelghani";
var inner=function()
return inner;

var testFunction=outer();

In the above code snippet , a function inner is defined inside another function outer , the local variable name is available even after function outer returns.

The result of the following line


and the result of the following line


is mabdelghani
Which means that the inner function which is referenced by testFunction doesn’t keep a copy of the name variable and it references the value of the local variable inside outer function though that function is returned.

It’s not necessary that the local variables in closures are to be declared before the inner function, They can be declared anywhere in the outer function before returning from it.

the following links are useful to know more about Javascript closures

Leave a Comment »

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at | The Pool Theme.
Entries and comments feeds.


Get every new post delivered to your Inbox.

%d bloggers like this: