Open this example in the interactive library
Source code
const counter = () => {
let n = 0;
return () => ++n;
};
const next = counter();
console.log(next(), next());
Sample output
1 2

Create a closure counter. A self-contained example using the JavaScript runtime.
Open this example in the interactive library
const counter = () => {
let n = 0;
return () => ++n;
};
const next = counter();
console.log(next(), next());
1 2