DEV Community

Geo Mukkath
Geo Mukkath

Posted on

Explaining JavaScript closures in one simple program. 3 minute read.

Closures are nothing but functions plus it’s lexical scope.

Let’s look at an example to understand closures.

function outer(){

  let a = 5;
  function inner(){
    console.log('inner', a);
  }
  inner();
}

outer();

//prints 'inner', 5
Enter fullscreen mode Exit fullscreen mode

Here we have a function called outer.

We have an inner function called ‘inner’ which simply logs inner with a variable a.
The variable a is declared outside the inner function.

We call inner inside the outer function.

When we call the outer function it simply prints the log. That’s simple.

I’ve modified the code below. Now think of an answer.

function outer(){

  let a = 5
  function inner(){
    console.log('inner', a);
  }
  return inner;
}

let y = outer();

y();
Enter fullscreen mode Exit fullscreen mode

It prints the exact same thing.

I have declared a variable y which stores the outer function and I call y later.
Here when I return inner, the value that get stored in the variable y must only be inner.
How does it remember a ? a is outside inner, despite that it remembers a.

This is called closure. The closure of inner is the function itself + its lexical scope.

Top comments (0)