Counter with Closure
Write a JavaScript function createCounter that takes a starting number and returns a counter function. Each time the counter function is called, it increments the count by 1 and returns the new value. The count must be private and only accessible through the closure.
This is a classic example of JavaScript closures — the returned function "closes over" the count variable, maintaining private state between invocations. The variable is not accessible from outside the returned function, creating true encapsulation. This pattern is fundamental in JavaScript for creating stateful functions without relying on classes or global variables.
The closure captures the count variable by reference, not by value. Each call to createCounter creates a new independent scope with its own count. Multiple calls to createCounter produce independent counters that don't interfere with each other. This lexical scoping behavior is unique to languages with first-class functions and closures like JavaScript.
Time complexity is O(1) per call. Space complexity is O(1) per counter instance. The closure retains only the single count variable, making it memory efficient even for many counters.
Edge cases include negative starting values (decrementing is not required, only incrementing), very large numbers (JavaScript numbers safely handle integers up to 2^53), and ensuring the original count parameter is not mutated or exposed.
Example Input & Output
Start at 0, increment 3 times
Start at 10, increment once
Start at 5, increment 5 times
Start at 100, increment twice
Start at -3, increment 3 times
Algorithm Flow

Solution Approach
Create a counter using a closure that maintains private state. The outer function initializes a count variable and returns an inner function that increments and returns it. The closure captures the count variable, persisting it across calls.
Closures in JavaScript capture variables by reference. Each call to createCounter() creates an independent counter with its own private count. This implements the module pattern for data privacy.
Time O(1), Space O(1).
Best Answers
function solution(start) {
var count = start;
return function() {
return count++;
};
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
