title: JavaScript: Why does closure only happen if I assign the return function to a variable?
body: <p>Even after reading <a href="https://github.com/getify/You-Dont-Know-JS" rel="noreferrer">You don't know JS</a> and <a href="http://dmitrysoshnikov.com/ecmascript/javascript-the-core-2nd-edition/" rel="noreferrer">JavaScript: The Core</a> I still couldn't understand the behavior of the following code.</p>
  
  <p>Why, when I call <code>counter()()</code>, do I get no closure, but if I assign a variable to the result of <code>counter()</code>, like <code>var getClosure = counter()</code>, I then get a closure when calling <code>getClosure()</code>?</p>
  
  <pre><code>function counter() {
  
      var _counter = 0;
  
      function increase() { return _counter++ }
  
      return increase;
  }
  
  // Double ()() to call the returned function always return 0, so no closure. 
  counter()() // returns 0
  counter()() // returns 0
  counter()() // returns 0
  counter()() // returns 0
  
  var createClosure = counter();
  
  createClosure() // returns 0
  createClosure() // returns 1
  createClosure() // returns 2
  createClosure() // returns 3
  </code></pre>