Closures in JS

Closures in JS

In this article I am going to walk you through Closures one of the important concept in JavaScript. By the end of this article you will get an idea about closures.

What is closure?

A function along with its lexical scope bundled together forms a closure. In simple words a closure gives you access to an outer function's scope from an inner function.

Let's understand this with an example

Illustration:

function x(){
    var a = 7;
    function y(){
        console.log(a);
     }
     return y;
 }
  var z = x();
  console.log(z);
  z();                             //output: 7

Output:

closuress.png

Note: You can also return a function inside a function.

Let's understand the above code snippet

  • We have an outer function x() which creates a global scope for everything which resides inside it.

  • Function x() contains an inner function y() which creates its local scope within its global scope. It references variable 'a' in its definition.

  • When functions are returned from another function they still maintain their lexical scope. They remember where they were actually present.

  • When function y() is returned, a closure was returned which contains function along with its lexical scope. So when y() is returned it has access to its scope along with its parent's scope(i.e.x()).

  • When y() runs it tries to find the 'a' in its local memory store, if it does not find it there then it goes to its parent's lexical scope and if found a's value is printed.

After returning the x(),x no longer resides in the call stack, still y() remembers its lexical scope where it came from and this is nothing but closure at work!

If you don't know what is lexical scope, I would recommend you to read my blog about scopes and lexical environment. (cr07.hashnode.dev/scope-scope-chain-and-lex..)

The famous setTimeout() function:

Let's see the one of the most important and frequently asked example of closure.

function delay(){
     var i = 'hello';
     setTimeout(function (){
         console.log(i);
     },3000);
    console.log('world');
}
delay();

Output:

world
hello                   // delay 3s
  • Function inside setTimeout forms a closure. It remembers the reference to 'i' so whenever this function goes it takes the reference of 'i' along with it.

  • setTimeout takes the function and stores it into some place and attaches timer to it and JavaScript proceeds, it does not wait for anyone. It goes to next line and prints "world".

  • Once the timer expires(3000) it takes that function and puts it in the call stack and run that function hence, printing "hello" in the console.

That's it for this article, hope you have got an idea about closures. You can read more about closures with curring,module design pattern,memoize,etc.