What the heck is Closure?
Let me first explain what exactly closure is?
Closure is function inside another function that has access to variables and parameters of outer function even after the outer function has returned.
Let me give you a simple example:-
Therefore, inner function which is get assigned to variable “getName” has access to outer function variables.
1.Using Private variable : The most important use case of closure is while creating private variables instead of global variable. Let me explain with example.
Here, in first example counterIncrement function is global varibale(counter) to increment the count. We can achieve the same behavior using private variable i.e. using closure & self-invoked function.
Note: “Self-invoked” function is invoked or called automatically after its decleration. The execution of such an anonymous function is done by enclosing it in a parenthesis set followed by another set of parenthesis.
2. Using throttle : Closure can be used to implement throttle functionality.
Throttling is a way to put limitation on a function to get executed maximum number of times over a span of time.
Eg. screen resize event handler(updateSize) can be called maximum 60 times in 1 minute as limit is 1 second for throttle.
3. Using debounce : Closure can be used to implement debounce functionality.
Debouncing is a way to block function execution until a certain amount of time has passed.
Eg. Search API method(searchProduct) will be delayed by 1 sec i.e. will remain blocked even if it get called before 1 sec.