Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
How do closures capture variables in JavaScript functions?
Asked on Mar 26, 2026
Answer
Closures in JavaScript allow a function to capture and remember its lexical environment, even after the function has finished executing. This means a function can access variables from its outer scope even after that scope has closed.
// Example of a closure capturing a variable
function outerFunction(outerVariable) {
return function innerFunction(innerVariable) {
console.log("Outer Variable: " + outerVariable);
console.log("Inner Variable: " + innerVariable);
};
}
const newFunction = outerFunction("outside");
newFunction("inside");
// Output:
// Outer Variable: outside
// Inner Variable: insideAdditional Comment:
✅ Answered with JavaScript best practices.- The "outerFunction" creates a closure by returning the "innerFunction".
- The "innerFunction" captures the "outerVariable" from its lexical scope.
- When "newFunction" is called, it still has access to "outerVariable" even though "outerFunction" has finished executing.
- Closures are useful for data encapsulation and creating private variables.
Recommended Links:
