javascript / intermediate
Snippet
Encapsulating State using Closures
Closures allow a function to 'remember' the environment in which it was created. Here, the variable 'count' is inaccessible from the outside world, providing a pattern for private state without classes.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
function createSecureCounter() {let count = 0;return {increment: () => ++count,getCount: () => count};}const counter = createSecureCounter();console.log(counter.increment()); // 1// console.log(count); // ReferenceError
Breakdown
1
let count = 0;
A local variable defined within the scope of the outer function.
2
return { increment: ... };
Returns an object containing functions that still have access to the local variable.
3
const counter = createSecureCounter();
Creates an instance where the 'count' state is preserved across calls.