definition of closure code example

Example: closure

var counter = (function() {  //exposed function references private state (the outer function’s scope / lexical environment) after outer returns. 
 var privateCounter = 0;
 function changeBy(val)   { privateCounter += val; }
 return {  increment: function() {changeBy(1); },
           decrement: function() {changeBy(-1);},
           value: function() {return privateCounter; }
  };
})();

counter.increment(); counter.increment();
counter.decrement();
counter.value();      //  1