Closure in JavaScript with Real Example

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.