Saturday, December 22, 2018

Understanding closures in JavaScript

In this tutorial we are going to discuss what is closure in javascript. A Closure is the aggregate of functions clumped together with the references to its surrounding environment. It gives you an outer function’s scope from an internal function. Scopes are contexts of variables.

NOTE :- Inner function can access variables and parameters of an outer function (however, cannot access arguments object of outer function).


What is a closure?

A closure is a feature in JavaScript where an inner function has access to the outer (enclosing) function’s variables — a scope chain.
The closure has three scope chains:
  1. it has access to its own scope — variables defined between its curly brackets
  2. it has access to the outer function’s variables
  3. it has access to the global variables

When to use Closure?

Closure is useful in hiding implementation detail in JavaScript. In other words, it can be useful to create private variables or functions.

Lets see the simple example for closure:

function outerFunction(name){
    return function (topic) {
        console.log(`Understanding ${topic} in ${name}`);
    }
}
outerFunction('Javascript')('Closure');

Output :
-------------------------
> "Understanding Closure in Javascript"


Example- 1 :

In this example, inner function accessing the variable of outer function.
function OuterFunction() {

    var outerVariable = 100;

    function InnerFunction() {
        console.log(outerVariable);
    }

    return InnerFunction;
}
var innerFunc = OuterFunction();
//calling function
innerFunc(); // 100

Output :
-------------------------
> 100
 

Example -2 :

In this example we are increment the counter variable, using inner function.
function Counter() {
    var counter = 0;

    function IncreaseCounter() {
        return counter += 1;
    };

    return IncreaseCounter;
}

var counter = Counter();
// calling function
console.log(counter())
console.log(counter())
console.log(counter())
console.log(counter())

Output :
-------------------------
> 1
> 2
> 3
> 4

Example- 3 :

In this example we have created private functions & variable inside the closure function.
  • privateCounter is private variable.
  • changeBy is private function.

// self invoking function
var counter = (function() {
  var privateCounter = 0;
  function changeBy(val) {
    privateCounter += val;
  }
  return {
    increment: function() {
      changeBy(1);
    },
    decrement: function() {
      changeBy(-1);
    },
    value: function() {
      return privateCounter;
    }
  };   
})();

// calling function...
console.log(counter.value()); // 0
counter.increment();
counter.increment();
console.log(counter.value()); // 2
counter.decrement();
console.log(counter.value()); // 1

This is all about closure in javascript. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.


No comments:

Post a Comment