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 counter1function createCounter() { // Private variable - only accessible via returned methods2 let count = 0; // Return an object with methods that form a closure3 return { // Each method has access to the private count variable4 increment: () => ++count,5 decrement: () => --count,6 get: () => count7 };8}// Create a new counter instance9const counter = createCounter();// Increment twice: 0 -> 1, then 1 -> 210console.log(counter.increment());11console.log(counter.increment());// Get current value: 212console.log(counter.get());Output
1 2 2
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