what is closures code example

Example 1: what is closure in javascript

function OuterFunction() {

    var outerVariable = 100;

    function InnerFunction() {
        alert(outerVariable);
    }

    return InnerFunction;
}
var innerFunc = OuterFunction();

Example 2: closure in javascript

function makeFunc() {
  var name = 'Mozilla';
  function displayName() {
    alert(name);
  }
  return displayName;
}

var myFunc = makeFunc();
myFunc();

Example 3: 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