Recall Nested function: function created inside another function.
=>
A closure is the combination of a function bundle together (enclosed) with reference to its surrounding state (Lexical Environment).
In other words, a closure give you access to outer function's scope from an inner function.
In JavaScript closures are created everytime a function is created, at a function creation time.
Whenever a inner function is return, lexical scope of its outer function is as well return this is a closure.
const firstname = 'Tina';
function makeFunc() {
const lastname = 'Xing'; // free variable
function display(greeting) {
console.log(`${greeting} from ${firstname} ${lastname}`);
}
return display;
}
const myFunc = makeFunc();
myFunc('Hello'); // Hello from Tina Xing
Free Variable
Free variable are those variables that are neither (locally declared, passed as parameter) nor in global environment.