Let’s take a look at how this is done. Open up your script and clear it. Add this bit of code.
function outerFunction( val1 )
function innerFunction( val2 )
return val1 + val2;
var foo = outerFunction( 'Jasko' );
document.write( foo( ' Koyn' ) );
Here we have a function named outerFunction(). It has 1 parameter which can take in any value. It doesn’t really matter. Inside this function, we define another function named innerFunction(). This function also has 1 parameter which can be any value. This function returns the result of val1 and val2.
Lastly, our outerFunction() returns the innerFunction(). So, when we call outerFunction(), do you have an idea of how everything will be executed? Let’s see if you’re right.
We next create a variable named foo. This is assigned the result returned from outerFunction(). Notice that I pass in a string. The result ends up being that we’re returned innerFunction().
Even though our function is finished executing, we still have access to the variables inside this function. It actually isn’t destroyed like most function calls are. Since foo is equal to innerFunction(), then we can use it like a regular function. This can be seen at the last line of our code.
Notice that we’re accessing val1 even though val1 is a parameter of the outerFunction(). You actually get access to the variables and parameters of the outer function.
Why isn’t the innerFunction() execute it even though we return it?
The innerFunction() is just simply returned it doesn’t execute even though you return it. This makes our variable usable as a function.
That’s it! Closures are used in popular libraries such as JQuery. When you use a simple function, any variables created inside that function are set to null and are eligible for garbage collection. When you use closures, all variables are still there and you can use them. To use closures, you just return a function that’s located inside the outer function.
More examples of closures will be shown in future tutorials so you can get used to them. More information about closures can be found here.