Closure Counter in JavaScript

Level 5409 keystrokes

This creates a counter using closures to maintain private state.

JavaScript code

// Factory function that creates a counter object
// initialValue has a default of 0 if not provided
1function createCounter(initialValue = 0) {
// Private variable - only accessible via returned methods
// This is the closure - count persists after function returns
2 let count = initialValue;
3
// Return an object with methods that access count
4 return {
// Each method forms a closure over count
5 increment() {
6 count++;
7 return count;
8 },
9 decrement() {
10 count--;
11 return count;
12 },
13 getCount() {
14 return count;
15 },
// Reset uses initialValue which is also in the closure
16 reset() {
17 count = initialValue;
18 return count;
19 }
20 };
21}
22
// Create a counter starting at 10
23const counter = createCounter(10);
// 10 + 1 = 11
24console.log(counter.increment());
// 11 + 1 = 12
25console.log(counter.increment());
// 12 - 1 = 11
26console.log(counter.decrement());
// Reset to initial value 10
27console.log(counter.reset());

Output

11
12
11
10
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this JavaScript code and how often they appear.

  • ;× 14
  • (× 14
  • )× 14
  • .× 8
  • {× 6
  • }× 6
  • =× 4
  • ,× 3
  • -× 2
  • +× 2

More JavaScript examples at level 5

← JavaScript typing practice