function - Does the order of var in the javascript context matter? -


maybe it's stupid, feel depressed 'var' keyword. have trouble in figuring out following problems:

var local = true; function outer() {     /* local scope */     var local = false;     function inner() {       alert(local);       var local;     }     inner(); } outer();  function a(x) {     return x * 2; } var a; alert(a); 

any explanations appreciated.

annotated source; i'm assuming code starts out @ global scope:

var local = true;      // creates global variable called `local` function outer() {     /* local scope */     var local = false; // creates local `local` within `outer`, shadowing (hiding) global     function inner() {       alert(local);    // alerts "undefined", value of `inner`'s `local`       var local;       // creates local `local` within `inner`, shadowing (hiding) `outer`'s version     }     inner(); } outer();  function a(x) {        // creates global function `a`     return x * 2; } var a;                 // has no effect alert(a);              // alerts function source (on engines have it) 

there 3 things @ work in code above:

  1. a declaration in nested scope shadows (hides) declaration in containing scope. local in outer shadows global, , local in inner shadows outer's local.

  2. var declarations processed when execution enters execution context, not appear in source code. they're said "hoisted" because moved (raised, hoisted) top of context in occur. (more: poor misunderstood var) effect particularly noticeable within inner function, because local being alerted 1 inner, not 1 outer (which why it's undefined), though declaration underneath alert.

  3. function declarations create symbol in scope in they're defined, in same symbol space var declarations do. (specifically, both create entries in binding object of lexical environment of execution context in occur.) if have function declaration , var same name (as a @ end of code), there's conflict. wins? function declaration wins, because of order dictated §10.5 of specification, says function declarations occur before var declarations, , var symbol that's defined doesn't override it.


Comments