Code Logo

Counter with Closure

Published at25 Jul 2026
JavaScript Functions Medium 0 views
Like0

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

Example 1
Input
0
Output
[0,1,2]
Explanation

Start at 0, increment 3 times

Example 2
Input
10
Output
[10]
Explanation

Start at 10, increment once

Example 3
Input
5
Output
[5,6,7,8,9]
Explanation

Start at 5, increment 5 times

Example 4
Input
100
Output
[100,101]
Explanation

Start at 100, increment twice

Example 5
Input
-3
Output
[-3,-2,-1]
Explanation

Start at -3, increment 3 times

Algorithm Flow

Recommendation Algorithm Flow for Counter with Closure
Recommendation Algorithm Flow for Counter with Closure

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.

function createCounter() {
  var count = 0;
  return function() { count++; return count; };
}

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

javascript - Approach 1
function solution(start) {
  var count = start;
  return function() {
    return count++;
  };
}