Lexical scope

by Jorge Bustos Pereda

HTML

The value of var a is recovered from the same place where the function was defined, not from the place where the function is executed.
<pre>
    foo:  <b id="foo"></b>
    foo2: <b id="foo2"></b>
    foo3: <b id="foo3"></b>
</pre>

JavaScript

function foo() {
    // console.log( a ); // 3 (not 2!)
    $('#foo').html(a);
}



function bar() {
    var foo2 = function() {
        // console.log( a ); // 3 (not 2!)
        $('#foo2').html(a);
    }
    function foo3() {
        // console.log( a ); // 3 (not 2!)
        $('#foo3').html(a);
    }

    var a = 2;
    foo();
    foo2();
    foo3();
}

var a = 1;
bar();