Closure
- A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment)
- A closure gives you access to an outer function’s scope from an inner function
- Consider example:
function makeFunc() {
const name = "Mozilla";
function displayName() {
console.log(name);
}
return displayName;
}
const myFunc = makeFunc();
myFunc();
- In general
name should be destroyed as soon as init is finished executing, hence this should not work but that does not happen
- Most probably? The Garbage collector does not dispose off the variable
name even after it is out of scope since it is being used in closure
Internal Working of Closure
References