Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
How do closures work in JavaScript and why are they useful? Pending Review
Asked on May 02, 2026
Answer
Closures in JavaScript are functions that have access to variables from another function's scope, even after that function has finished executing. They are useful for data encapsulation and creating private variables.
<!-- BEGIN COPY / PASTE -->
function createCounter() {
let count = 0;
return function() {
count += 1;
return count;
};
}
const counter = createCounter();
console.log(counter()); // Output: 1
console.log(counter()); // Output: 2
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- Closures allow the inner function to access the outer function's variables ("count" in this example) even after the outer function has executed.
- They are useful for creating private variables, as the "count" variable is not directly accessible from outside the "createCounter" function.
- Closures help in maintaining state between function calls, as shown by the incrementing "count" variable.
Recommended Links:
