In javascript, when a function returns another function, a function that returned can access the variables inside the other function. This is called closure.
function counter(){
var number = 0;
return function consoleIt(){
debugger
number += 1
console.log(number)
}
}
In this example inside the counter function there is a variable named number and this function returns another function. We invoke the counter function and assigned consoleIt function to the increment variable.But there is one more thing. Now consoleIt function can access the number variable. You can see this if you put debugger inside the consoleIt function.
Whenever we invoke increment function, number variable will be increased by one.
What is the benefit of closure?
You can give memory to functions. Whenever function invoked, it can remember variables from past invokes.
For example;
const debounce=(debounceFn,timeout)=>{
var timeoutId
return function(...args){
clearTimeout(timeoutId);
timeoutId=setTimeout(() => debounceFn(...args),timeout)
}
}
const debouncedHandleSearch = debounce(handleSearch,300)
Whenever we invoke debouncedHandleSearch function, it will remember timeoutID and clear it.
Thanks for reading it. You can see my other post below.
Top comments (0)