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

geomukkath

Geo Mukkath

Posted on December 8, 2022

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.

💖 💪 🙅 🚩
geomukkath
Geo Mukkath

Posted on December 8, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Understanding JavaScript Closures
webdev Understanding JavaScript Closures

September 19, 2024

What Are JavaScript Closures?
webdev What Are JavaScript Closures?

August 29, 2024

# "JavaScript Closures: Demystified."
javascript # "JavaScript Closures: Demystified."

September 22, 2023