capypad
0 day streak
javascript / intermediate
Snippet

Private State with Closures

A closure is created when an inner function references variables from its outer scope, allowing for private data encapsulation.

snippet.js
javascript
1
2
3
4
5
function createCounter() {
let count = 0;
return () => ++count;
}
const counter = createCounter();
Breakdown
1
let count = 0;
Variable defined in the lexical environment of the outer function.
2
return () => ++count;
Returns a function that maintains access to 'count'.