Closures Ex 1

See also http://stackoverflow.com/questions/111102/how-do-javascript-closures-work

by Shaun Luttin

HTML

Whenever you see the function keyword within another function, the inner function has access to variables in the outer function. <strong>That is a closure</strong>. A function doesn't have to return in order to be called a closure. <strong>Simply accessing variables outside of your immediate lexical scope creates a closure.</strong>

<pre>
    
    Values over Time
    
    x = 2
    tmp = 3
    y = 10
    tmp = 4
    alert = x + y + tmp = 16    
    
</pre>

JavaScript

function foo(x) {    
    var tmp = 3;    
    function bar(y) {
        // bar has access to x and tmp
        alert(x + y + (++tmp));
    }    
    bar(10);
}
foo(2);