Closure means that an inner function always has access to the vars and parameters of its outer function, even after the outer function has returned.

var Counter = (function(){
let counter = 0;
return function(){
return counter += 1;
}
})()
console.log(Counter())
console.log(Counter())
console.log(Counter())

Note:- Function following by () means self invoking, It means outer function invoked single time. Means counter initialized by 1. After this all console call inner function it will increase one by one.

If you want to increase the count on the button click. It’s a real example of closure.

Ankit Kumar Rajpoot

I’m a MERN Developer. ( Redux | AWS | Python ) I enjoy taking on new things, building skills, and sharing what I’ve learned.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store