Counter Function
EasyPrompt
Write a function called createCounter
that takes an optional starting value and returns a counter function. Each time the counter function is invoked, it should return a number that's one higher than the previous invocation. If a starting value is provided, the counter begins from that value otherwise, it starts from zero.
Example
const counter = createCounter();
counter(); // 0
counter(); // 1
counter(); // 2
With a custom starting value:
const counter = createCounter(3);
counter(); // 3
counter(); // 4
counter(); // 5
Playground
Use a variable inside the outer function to store the count value between function calls.
Don't forget to handle the case when no starting value is provided.
Solution
Explanation
Let's break down the solution step by step:
- We create a function
createCounter
that takes an optionalstartValue
- Inside this function, we initialize a variable
count
with the starting value, or 0 if no value is provided - We then return a new function that:
- Returns the current value of
count
- Increments
count
for the next call
- Returns the current value of
The key to this solution is the post-increment operator (count++
). This operator returns the value of count
first, and then increments it after the return. This gives us exactly the behavior we need - returning the current count and preparing the next value in a single statement.
When we call createCounter()
, it sets up a new counter starting at 0. When we call createCounter(3)
, it sets up a new counter starting at 3. Each counter maintains its own separate count.
This is a simple example of a closure in JavaScript - the inner function "remembers" and has access to the count
variable even after the outer function has finished running. This allows us to create multiple independent counters that each keep track of their own state.