title: JavaScript while loop in console prints extra results
body: <p>Can anyone explain why the following code works when run as part of function, but it produce strange result when run by itself in the Chrome Console window? </p>
  
  <pre><code>var foo = function() { 
      var x = 1;
      while (x&lt;3) { 
          console.log(x);
          x = x+1;
      }
  }
  
  foo(); // This prints 1,2 as expected
  </code></pre>
  
  <p>But when I run just <code>while</code> part directly in Chrome Console I get 1,2,3 which makes no sense (see image for the output):</p>
  
  <pre><code>    var y = 1;
      while (y&lt;3) { 
          console.log(y);
          y = y+1;
      }
  
      // This prints 1,2,3 in the console
  </code></pre>
  
  <p><img src="https://i.stack.imgur.com/Ovdg0.png" alt="enter image description here"></p>
  
  <p>Note that there somewhat similar question about <code>console.log</code> resulting in <code>undefined</code> (<a href="https://stackoverflow.com/questions/14633968/chrome-firefox-console-log-always-appends-a-line-saying-undefined">Chrome/Firefox console.log always appends a line saying undefined</a>), but there is no function call in my sample and <code>while</code> does not ever return any value.</p>