How do JavaScript closures work?
Asked on Jul 05, 2024
Answer
Closures in JavaScript are a fundamental concept where an inner function has access to variables from its outer function scope, even after the outer function has finished executing.
<!-- BEGIN COPY / PASTE -->
function outerFunction(outerVariable) {
return function innerFunction(innerVariable) {
console.log("Outer Variable: " + outerVariable);
console.log("Inner Variable: " + innerVariable);
};
}
const closureExample = outerFunction("outside");
closureExample("inside");
<!-- END COPY / PASTE -->
Additional Comment:
✅ Answered with JavaScript best practices.- The "outerFunction" returns "innerFunction", which is a closure.
- "innerFunction" retains access to "outerVariable" even after "outerFunction" has executed.
- When "closureExample" is called, it logs both "outerVariable" and "innerVariable".
- Closures are useful for data encapsulation and creating private variables.
Recommended Links:
← Back to All Questions