Closure Counter in JavaScript

Level 4253 keystrokes

Closures allow functions to access variables from their outer scope even after it returns.

JavaScript code

// Factory function that creates a counter
1function createCounter() {
// Private variable - only accessible via returned methods
2 let count = 0;
// Return an object with methods that form a closure
3 return {
// Each method has access to the private count variable
4 increment: () => ++count,
5 decrement: () => --count,
6 get: () => count
7 };
8}
// Create a new counter instance
9const counter = createCounter();
// Increment twice: 0 -> 1, then 1 -> 2
10console.log(counter.increment());
11console.log(counter.increment());
// Get current value: 2
12console.log(counter.get());

Output

1
2
2
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.

  • (× 11
  • )× 11
  • ;× 6
  • .× 6
  • =× 5
  • :× 3
  • >× 3
  • -× 2
  • ,× 2
  • {× 2

More JavaScript examples at level 4

← JavaScript typing practice