Putting a closure to JS Closures

a closure is the local variables for a function – kept alive after the function has returned.

I’m wrapping my head around JS & jQuery Closures. From the definition above my understanding is a closure allows access to variables outside a function without the need for creating globals, eliminating the inherent risk. Is my interpretation correct?

As always many thanks.


Normally you would think that when you define a function foo the only possible variables that it could read/write are the parameters you pass in to the function when it’s called foo(1, "hello"); and all the global variables you defined. This is how C-like languages work.

In JavaScript however, you can define a function pretty much anywhere and other than global and parameter variables the function can also read/write variables in its parent scopes; for example:

var global = "global";
function foo() {
    var one = 1;
    function bar() {
        var two = 2;
        function argh() {

The function argh will be able to read/write variables from all its parent scopes, in this case two, one and global are all accessible to the function argh.

I hope this better explains what closures are about – it’s not that hard once you under how scoping works in JavaSript. Closures are basically just inner functions that are able to access current and parent scopes… :).

This is quite a powerful concept especially for when you’re doing asynchronous things. Imagine yourself having to define a function that will run in a different moment in time:

// the function we defined below
// will run in 5 seconds in time

}, 5000);

Without the ability of JavaScript functions to access parent scopes we would only be able to access global variables. However with JavaScript this is much easier and we can use all available local variables:

var foo = "some local variable";
}, 5000);