Come Closure in Javascript

Come Closure in Javascript
Come Closure in Javascript

A closure is a feature of Javascript where inner function has access to the outer (enclosing) function’s variables—scope chain. This scope chains means inner function has access to:

  • its own scope (variables defined between its curly brackets and its parameters),
  • the outer function’s variables and parameters, 
  • the global variables.

Now we will look into it in detail. Consider following example:

var globalVar = "xyz";

  function outerFunc(outerArg) {

    var outerVar = 'Alex';

    function innerFunc(innerArg) {

      var innerVar = 'Chris';
      console.log("globalVar = " + globalVar);
      console.log("outerArg = " + outerArg);
      console.log("innerArg = " + innerArg);
      console.log("outerVar = " + outerVar);
      console.log("innerVar = " + innerVar);
    }
    innerFunc(456);

  }
  outerFunc(123);

In this example, inside the inner function innerFunc, we have access to

  • its own scope(innerVar and innerArg)
  • outer function outerFunc variable(outerVar) and parameter(outerArg)
  • and global variable(globalVar)

Remember : In hoisting, when a function executes and it encounter a variable,it looks for it in its own scope first, if it doesn’t find, it searches in outer function’s scope and finally in global scope.

Closure is when a function is able to remember and access its lexical scope even when that function is executing outside its lexical scope. e.g:

  function foo() {
    var a = 2

    function bar() {
      console.log(a) // 2
    }
    bar()
  }
  foo()

Even after outer function is return, closure has access to outer function’s scope. For e.g:

function outer(a) {
      var b = 10;
      function inner() {
            var c = 20; 
            console.log(a+b+c);
       }
    return inner;
  }
  var add = outer(5);   // inner function will be assigned to add
  console.log(add); // ƒ inner() {
                      var c = 20;
                      console.log(a+b+c);
                     }
  console.log(typeof add);   // function

  add();   // output 35

The inner function can access the variables (b) of the enclosing function and the parameter (a) due to closures in JavaScript. So inside the inner function we have value of a = 5 and b=10, when the outer (5) was executed. Since we have values of a and b due to closure, also c is a inner variable so Javascript engine can calculate a+b+c which is equal to 35. Let us then consider code which brings closure into full light:

  function foo() {
    var a = 2

    function bar() {
      console.log(a)
    }
    return bar
  }
  var baz = foo()
  baz() // 2 

After we execute foo(), we assign the value it returned (our inner bar() function) to a variable called baz, and then we actually invoke baz(), which of course is invoking our inner function bar().After foo() executed, normally we would expect that the entirety of the inner scope of foo() would go away.But the “magic” of closures does not let this happen. That inner scope is in fact still “in use”, and thus does not go away. Who’s using it? The function bar() itself.By virtue of where it was declared, bar() has a lexical scope closure over that inner scope of foo(), which keeps that scope alive for bar() to reference at any later time.bar() still has a reference to that scope, and that reference is called closure.
Functions can be passed around as values, and indeed invoked in other locations, are all examples of  closure. Consider following code:

  function foo() {
    var a = 2;

    function baz() {
      console.log(a); // 2
    }

    bar(baz);
  }

  function bar(fn) {
    fn(); // here is the magic of closure!
  } 

  foo();  

We pass the inner function baz over to bar, and call that inner function (labeled “fn” now), and its closure over the inner scope of foo() is observed, by accessing a.

Hope this article was helpful. Thank you!!

0 Shares:
Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like