A function in JavaScript has access to any variables defined in the outer scope.
function outerFunction(arg) {
var variableInOuterFunction = arg;
function bar() {
console.log(variableInOuterFunction); // Access a variable from the outer scope
}
// Call the local function to demonstrate that it has access to arg
bar();
}
outerFunction("hello closure"); // logs hello closure!
But here is the awesome part: the inner function can access the variables from the outer scope even after the outer function has returned.
This is because the variables are still bound in the inner function and not dependent on the outer function. In other words, the variable was captured.
function outerFunction(arg) {
var variableInOuterFunction = arg;
return function() {
console.log(variableInOuterFunction);
}
}
var innerFunction = outerFunction("hello closure!");
**// Note the outerFunction has returned**
innerFunction(); // hello closure!
It allows you to compose objects easily
function createCounter() {
let val = 0;
return {
increment() { val++ },
getVal() { return val }
}
}
let counter = createCounter();
counter.increment();
console.log(counter.getVal()); // 1
counter.increment();
console.log(counter.getVal()); // 2
It’s kind of like React function component.