Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
How do closures work in JavaScript and when should I use them?
Asked on Jan 25, 2026
Answer
Closures in JavaScript occur when a function retains access to its lexical scope, even when the function is executed outside that scope. They are useful for data encapsulation and creating private variables.
<!-- BEGIN COPY / PASTE -->
function createCounter() {
let count = 0;
return function() {
count++;
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.- In this example, "createCounter" is a function that returns another function, which forms a closure.
- The inner function retains access to the "count" variable, even after "createCounter" has finished executing.
- Closures are useful for creating private variables and functions, as shown in the example where "count" is not accessible directly from outside.
- Use closures when you need to maintain state between function calls or when you want to encapsulate functionality.
Recommended Links:
