Site icon i2tutorials

Javascript-Closure

Javascript-Closure

 

The javascript closure defines that an inner function and always has access to the vars, parameters of its outer function. Even after the outer function has returned.

The inner function can access variables and/or parameters of an outer function (can’t access the arguments object of the outer function).

 

Example:

 

InnerFunction() can access outerVariable.

function OuterFunction() {

  var outerVariable = 1;

  function InnerFunction() {
    alert(outerVariable);
  }

  InnerFunction();
}

 

InnerFunction() can access the outer variable even if it will be executed separately.

Example: Closure

 

Example: Closure

 

<!DOCTYPE html>
<html>
<body>
      <h1>Demo: Closure</h1>
      <script>
      function OuterFunction() {

             var outerVariable = 100;

             function InnerFunction() {
                    alert(outerVariable);
             }

             return InnerFunction;
      }
      var innerFunc = OuterFunction();

      innerFunc();
      </script>
</body>
</html>

 

OUTPUT:

 

100

 

Javascript return InnerFunction; provides the InnerFunction() from OuterFunction() when you call OuterFunction(). A variable innerFunc reference the InnerFunction() only and not the OuterFunction(). So now, when we call innerFunc(), it can still access outerVariable which is declared in OuterFunction(). This is called Closure.

 

The following is not a closure:

 

var Counter = (function () {
    var i = 0;
    return { counter : i += 1 };
})();

 

When to use Closure:

 

The javascript closure is useful in hiding implementation detail in JavaScript. It can be used to create private variables or functions.

 

Example:

<!DOCTYPE html>
<html>
<body>
       <h1>Demo: Closure</h1>
       <script>
       var counter = (function() {
        var privateCounter = 3;
        function changeBy(val) {
               privateCounter += val;
        }
        return {
              increment: function() {
               changeBy(1);
               },
               decrement: function() {
                changeBy(-1);
               },
               value: function() {
                return privateCounter;
               }
       };
      })();

      alert(counter.value());
      counter.increment();
      counter.increment();
      alert(counter.value());
      counter.decrement();
      alert(counter.value());
      </script>
</body>
</html>

 

OUTPUT:

 

3

5

4

Exit mobile version