
									 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.
 
 - Counter is initialized with starting value 5. 
 
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.
 
 - Two independent counters are created with different starting values. 
 
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
 
Editorial
									
												
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. | ||||
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