title: JavaScript Scope and Execution Context
body: <p>I am trying to understand JavaScript scope rules. What I have read in textbooks and the documentation is confusing.</p>
  
  <p>It seems to me that JavaScript is a statically (or lexically) scoped language - when trying to bind a variable name to a variable (definition), the lexical structure of the code is used.</p>
  
  <p>An execution context seems to be similar to a stack frame on the call stack. Each execution context has a variable object upon which all the local variables (of the associated function) are defined. These variable objects are linked together to provide a 'scope chain' from the variable object at the top of the stack to the variable object at the bottom of the stack (the window object). This scope chain is searched from top to bottom in binding variable names to variables. This is very similar to statically scoped languages like C/C++/Java.</p>
  
  <p>There seems to be one important difference with respect to C/C++/Java -- it is possible to access a variable defined in a function whose stack frame is no longer on the call stack, as shown in the example below:</p>
  
  <pre><code>var color = "red";
  var printColor;
  
  function changeColor() {
      var color = "green";
  
      printColor = function(msg) {
          alert(msg + color);
      }
      printColor("in changeColor context, color = ");  // "green"
  }
  
  changeColor();
  
  // stack frame for "changeColor" no longer on stack
  // but we can access the value of the variable color defined in that function
  
  printColor("in global context, color = ");  // "green"
  </code></pre>
  
  <p>Have I got this right? Are there other issues I should be aware of?</p>
  
  <p>Thanks in advance</p>