DEV Community

Raja B
Raja B

Posted on

Closures JS

closure

A closure is a feature in JavaScript where an inner function remembers and can access the variables of its outer function even after the outer function has finished executing

Why do we need Closures?

Closures help you:

  • Keep data private

  • Store values between function calls

  • Avoid using global variables

  • Create reusable functions

output

What happens?

const greet = outer();

  • outer() runs

  • message = "Hello"is created

  • inner() is returned

Normally, when outer() finishes, its variables should disappear

But they don't!

Because inner() still needs message

So JavaScript keeps message in memory

Then:
greet();

prints:

Hello

This is called a closure

Top comments (0)