Closures are a fundamental concept in JavaScript that allow functions to access variables from their outer scope. This article explains closures, their practical uses, and common pitfalls.
What Are Closures?
A closure is the combination of a function bundled together with references to its surrounding state.
function outerFunction(outerVariable) {
return function innerFunction(innerVariable) {
console.log(`Outer Variable: ${outerVariable}`);
console.log(`Inner Variable: ${innerVariable}`);
};
}
const closureExample = outerFunction("I am from outerFunction");
// Calling the inner function with the closure
closureExample("I am from innerFunction");