views:

56

answers:

2

In the following code, I can call baz. Also somewhere else I read "JavaScript has function-level scope". I know, Im confusing myself somewhere. Can somebody make me understand please?

/* An anonymous function used as a closure. */
var baz;
(function() {
    var foo = 10;
    var bar = 2;
    baz = function() { 
        return foo * bar; 
    };
})();

baz(); // baz can access foo and bar, even though it is executed outside of the
       // anonymous function

.

+4  A: 

The variable baz is declared outside the anonymous function (even if it isn't actually defined until you use the function expression to assign a value to it). This places its scope outside said function.

foo and bar are declared inside the anonymous function, which limits their scope to that function. The function assigned to baz can access them because they were in scope when it was created.

David Dorward
A: 

David explained it pretty well. Things that are in scope where you define baz, are still available after your anonymous function has returned.

Read about closures for more information.

nlogax