Javascript Closure
Closure in javascript is simply a function that has access to variables outside of its scope. Let's see an example below, in the example we see that the increment function has access to the value variable outside of it. This means that const increment = () => { value++} is a closure.
const increment = () => {
value++;
}
increment();
console.log(value); // 1
This is different from a pure function that doesn't depend on variables outside of its scope when this function runs, javascript only uses the variables inside of it.
function increment(value) {
value++;
}
increment(0);
console.log(value) // 1
let value = 0;
function increment() {
value++;
}
increment();
console.log(value) // 1
When the above function runs, Javascript will look outside for the variables and store them in memory so that when the function is run again, javascript knows the values of the variables outside of it. This means that closures require more memory than pure functions, but they are very useful for encapsulating data.
Closures are used for immediately invoked function expressions, factory functions, currying, and so much more.