JavaScript closure explained

Closures are a way to let a function have persistent, private variables – that is, variables that only one function knows about, where it can keep track of info from previous times.It is an inner function that has access to outer function variables and parameters in addition to its own variables in its scope. In simple words, it is a function inside another function. These functions could be named functions or Anonymous.
Here is a sample closure:
Think about a scenario where we need to keep track of the mouse click happened in a session on a page:

<script type="text/javascript">
    var incrementClickCount = (function () {
        var clickCount = 0;
        return function () {
            return ++clickCount;
        }
    })()
</script>
<input type="button" value="Click Me" onclick="alert(incrementClickCount());" />
Advertisements