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
What happens?
const greet = outer();
outer()runsmessage = "Hello"is createdinner()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)