Closures in JavaScript?

Closures in JavaScript?

In this article we are going to cover:

  • Lexical Environment
  • Closures
  • Uses of Closures

start.gif

function bundled together with its lexical environment is known as closures.

Lexical Environment

function a(){
    var x=100;
    function b(){
        console.log(x);
    }
    b();
}
a();

function a() has its local variable x=100 and the declaration of function b() but notice that b() does not have any variable still if we run this code we will get the output as 100. how is that possible?.... here comes the concept of lexical environment.

The lexical environment is just local memory along with the reference to its parent lexical environment.

As we know that every function has its own execution context and execution context divided into memory and code, the lexical environment is this memory along with reference to its parent lexical environment.

Because of this lexical environment if run this code the console.log() try to find x in its scope which is inside the function b() but he cannot find x. so, he refers to its parent lexical environment which is of function a(), and the variable is declared there so the output is getting print in the console without any errors.

Closure

function a(){
    var x=100;
    function b(){
        console.log(x);
    }
    return b;
}
var c=a();
c();

This code runs similar to the previous one. but as we know once the execution of a function is over its execution context is gone, poof!!!! so as from this concept when we call the function a() its execution context would be gone. still how we able to access the variable x if we call function c(). that's because the function b() forms the closure. Because of which even if the function is gone out of the call stack the value of variable x is stored inside closure.

If we go one level deep in scope and try to access variable let's see what happens

function c() {
  var y = 200;
  function a() {
    var x = 100;
    function b() {
      console.log(x, y);
    }
    b();
  }
  a();
}
c();

This program still able to access the value of y. because function b() forms another closure with function c().

Uses of Closures:

  • module design pattern
  • currying
  • data hiding and encapsulation
  • function like once
  • memoize
  • maintaining state in the async world
  • setTimeouts
  • iterators
  • and many more...

That's it for this article!

thank you.gif