Javascript Closures

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

Tags: Javascript



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() { alert(name); }; return inner; } var testFunction=outer(); alert(testFunction); testFunction();

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

alert(testFunction);

is

function()

{

alert(name);

}

and the result of the following line

testFunction();

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

http://www.jibbering.com/faq/faq_notes/closures.html

http://blog.morrisjohns.com/javascript_closures_for_dummies