Tutorialspoint
Problem
Solution
Submissions

Create Counter Function

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 8

Write a JavaScript program to create a counter function using closures. The function should return another function that increments and returns a counter value each time it's called. Each counter instance should maintain its own independent count.

Example 1
  • Input: counter = createCounter(5)
  • Output: counter() returns 6, counter() returns 7, counter() returns 8
  • Explanation:
    • Counter is initialized with starting value 5.
    • First call increments to 6 and returns 6.
    • Second call increments to 7 and returns 7.
    • Third call increments to 8 and returns 8.
Example 2
  • Input: counter1 = createCounter(0), counter2 = createCounter(10)
  • Output: counter1() returns 1, counter2() returns 11, counter1() returns 2
  • Explanation:
    • Two independent counters are created with different starting values.
    • counter1 starts at 0, counter2 starts at 10.
    • Each counter maintains its own state independently.
    • Calling counter1() returns 1, counter2() returns 11, counter1() returns 2.
Constraints
  • -1000 ≤ initialValue ≤ 1000
  • The counter function should use closures to maintain state
  • Each counter instance should be independent
  • Time Complexity: O(1) per function call
  • Space Complexity: O(1) per counter instance
Functions / MethodsTech MahindraShopify
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a closure to encapsulate the counter variable within the outer function scope
  • Return an inner function that has access to the counter variable
  • The inner function should increment the counter and return the new value
  • The counter variable will be preserved between function calls due to closure
  • Each call to createCounter should create a new independent closure

Steps to solve by this approach:

 Step 1: Create the outer function createCounter that accepts an initial value parameter.
 Step 2: Declare a local variable counter inside the outer function and initialize it with the initial value.
 Step 3: Return an inner anonymous function from the outer function.
 Step 4: Inside the inner function, increment the counter variable by 1.
 Step 5: Return the updated counter value from the inner function.
 Step 6: The closure mechanism ensures the counter variable persists between function calls.
 Step 7: Each call to createCounter creates a new independent closure with its own counter variable.

Submitted Code :