DEV Community

Geo Mukkath
Geo Mukkath

Posted on

2 1

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.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Cloudinary image

Zoom pan, gen fill, restore, overlay, upscale, crop, resize...

Chain advanced transformations through a set of image and video APIs while optimizing assets by 90%.

Explore

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay