Let’s learn closures today, How closures are define how they got intialize and how they work
A closure is a function within a function that has access to the environment that it was created, which gives the ability to access the private methods of outer function to their inner function. In simple words function which is return by another function called closures.
A closure is created when you define a function — not when you execute it. Then, every time you execute that function, its already-defined closure gives it access to all the function scopes available around it.
Let’s take a look at an example
Suppose we create a addCounter function, which increase count by 1:
But the problem is that with this above code any function can change the counter value without executing addCounter() method. which is not correct
The inner function plus() has access to the counter variable in the parent function
But when the addCounter() will get execute it will always make counter count 0. This is not our case. Our case is like we have to execute counter variable only at once, So that we increase counter by 1, Their closure will help us, We are creating below example using Immediately-invoked function expression (or IIFE, pronounced “iffy”)
The variable addCounter is assigned to the return value of a self-invoking function. Why did we put counter in an immediately-executed anonymous function? It makes counter private, which prevents accidental changes from the outside world. Like as we did in our first example where counter variable is global
The self-invoking function only runs once. It sets the counter to zero (0), and returns a function expression.
This way addCounter becomes a function. The cool part is that it can access the counter in the parent scope.
The counter is protected by the scope of the anonymous function, and can only be changed using the addCounter function.