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 provided1function createCounter(initialValue = 0) { // Private variable - only accessible via returned methods // This is the closure - count persists after function returns2 let count = initialValue;3 // Return an object with methods that access count4 return { // Each method forms a closure over count5 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 closure16 reset() {17 count = initialValue;18 return count;19 }20 };21}22 // Create a counter starting at 1023const counter = createCounter(10);// 10 + 1 = 1124console.log(counter.increment());// 11 + 1 = 1225console.log(counter.increment());// 12 - 1 = 1126console.log(counter.decrement());// Reset to initial value 1027console.log(counter.reset());Output
11 12 11 10
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