title: Declare a variable using 'var' in a with{ } statement
body: <p>I am just studying You-dont-know-js book on github, currently scope-closure, chapter2 : <a href="https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch2.md" rel="nofollow noreferrer">https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch2.md</a></p>
  
  <p>I encountered a problem that I am not clear: declare a variable using 'var' in a with{ } statement. 
  Here's the explanation regarding this:</p>
  
  <blockquote>
    <p>Note: Even though a with block treats an object like a lexical scope,
    a normal <strong>var declaration</strong> inside that with block will not be scoped
    to that with block, but instead the containing function scope.</p>
  </blockquote>
  
  <p>According to this explanation, I changed a little bit the code provided in this chapter:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>function foo(obj) {
   with (obj) {
    var a = 2;  //Here I added "var" declaration 
   }
    console.log('foo, '+ a)  //Here I added console function to see if a is in foo scope
  }
  
  var o1 = {
   a: 3
  };
  
  var o2 = {
   b: 3
  };
  
  foo( o1 );   // foo, undefined
  console.log( o1.a );     //2
  
  foo( o2 );   // foo, 2
  console.log( o2.a );    //undefined</code></pre>
  </div>
  </div>
  </p>
  
  <p>for foo(o2),  my understand is that because o2 has no property named 'a', the var declaration inside the with block just created a variable a within foo function scope, and the result makes sense.
  but for foo(o1), the var declaration just changed o1.a to value 2, but why console.log('foo, '+a)shows 'foo, undefined'? As I understand, the result should either be 'foo, 2' or reference error: a is not defined. </p>
  
  <p>Could anyone explain this issue? thanks.</p>