JS Built-ins
Closuresintermediate

Closures β€” Step counter

πŸ“– Usage Example
function makeStepCounter(step) {
  let n = 0
  return () => (n += step)
}
const byFive = makeStepCounter(5)
byFive()  // β†’ 5
byFive()  // β†’ 10
byFive()  // β†’ 15

Capturing a custom step in the closure means each produced counter advances by its own preset increment, independent of all others.

Counter with Custom Step

Create a counter that increments by a custom step value instead of always by 1.

Challenge: Create a makeStepCounter(step) function that returns a function. Each call increments by step and returns the new value.

Example:

const counter = makeStepCounter(5)
counter() // 5
counter() // 10
counter() // 15
πŸ’‘ Hints (2)
  • β€’ Store the step value in closure
  • β€’ Modify counter by adding step on each call