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?
Asked on May 08, 2026
Answer
Closures in JavaScript occur when a function is able to remember and access its lexical scope, even when that function is executed outside its original scope. They are useful for data encapsulation and maintaining state across function calls.
<!-- 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
console.log(counter()); // Output: 3
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- The "createCounter" function returns an inner function that has access to the "count" variable.
- Each time the returned function is called, it increments and returns the "count" variable, demonstrating closure.
- Closures are useful for creating private variables and functions, as they encapsulate the state within a function scope.
Recommended Links:
