Closure Counter

Easy
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: Closure Counter

Approach

Create a factory function that returns an object with increment, decrement, and getValue methods. Each returned method closes over a shared count variable, demonstrating how closures preserve access to their enclosing scope even after the outer function returns.

Complexity Analysis

Time
O(1)
Space
O(1)

Pattern

Closure Pattern

Why It Works

Inner functions retain a reference to outer variables even after the outer function returns. Each call to createCounter creates a new scope with its own independent count variable.

Updated Feb 2026