What is a closure?
a closure is a function that has access to variables from its surrounding scope. can be used to create reusable functions that can access data from other functions
function pureFunction(a, b) {
return a + b;
}
- not a closure, internal data (a, b) are kept in memory of the call stack until its popped off
let b = 3; // free variable
function impureFunction(a) {
return a + b;
}
- closure is created because a the impureFunction needs/has access to a variable in parent scope
- in order for interpreter to call this function and also know the value of the free variable, it creates a closure
- this closure is store in the heap memory, and is long-lived (garbage collected eventually) unlike the call stack
- also the reason why closures take up more memory and require more computation