title: How JavaScript closure works in this sample cases?
body: <p>I am relatively new with the Javascript closure concept.
  I know how to get the work done, but I want to understand the concept through and through.</p>
  
  <p>Can somebody explain in short, why example 1,2 works,and 3,4 doesn't?
  Any good links regarding js closures will be appreciated as well.</p>
  
  <p><strong>Example 1</strong></p>
  
  <pre><code>    var add = (function() {
      var counter = 0;
      var plus = function() {
               return ++counter;
           };
  
           return plus;
  
       })();
  
      console.log(add()); //1
      console.log(add()); //2
      console.log(add()); //3
  </code></pre>
  
  <p><strong>Example 2</strong></p>
  
  <pre><code>var add = (function () {
      var counter = 0;
      return function () {return counter += 1;}
  })();
  
  add();//1
  add();//2
  add();//3
  </code></pre>
  
  <p><strong>Example 3</strong></p>
  
  <pre><code>var add=function(){
  var counter=0;
  var plus=(function(){
    return ++counter;
  })();
  return plus;
  
  } 
   console.log(add());//1
   console.log(add());//1
   console.log(add());//1
  </code></pre>
  
  <p><strong>Example 4</strong></p>
  
  <pre><code>var add=function(){
  var counter=0;
  var plus=(function(){
    return ++counter;
  });
  
  return plus;
  }
  
  
  console.log(add()());//1
  console.log(add()());//1
  console.log(add()());//1
  </code></pre>