javascriptscoping

About scoping in JavaScript


I need to have some information about the scoping in JavaScript. I know that it supports lexical (static) scoping, but, does not it support dynamic scoping as well?


Solution

  • I think you're confused because Javascript uses static scoping but at function-level, not at block level like usual structured languages.

    var foo = "old";
    if (true) {var foo = "new";}
    alert (foo == "new")
    

    So be careful, blocks don't make scope! That's why you sometimes see loops with functions inside just to enable variables whose scope is inside an iteration:

    functions = [];
    for(var i=0; i<10; i++) {
       (function(){
           var local_i = i;
           functions[local_i] = function() {return local_i;}
       })();
    }
    functions[2]() // returns 2 and not 10