JS Built-ins
Closuresintermediate

Closures β€” Counter with reset

πŸ“– Usage Example
function makeCounter() {
  let n = 0
  return {
    increment() { return ++n },
    reset()     { n = 0 },
    value()     { return n },
  }
}
const counter = makeCounter()
counter.increment()  // β†’ 1
counter.reset()
counter.value()      // β†’ 0

Returning an object of methods from a closure lets multiple operations share the same private variable, forming a clean stateful API.

Counter with Control Methods

Extend the counter concept by returning an object with multiple methods that share access to the same internal state.

Challenge: Create a makeCounter function that returns an object with three methods:

  • increment() - increments counter by 1 and returns the new value
  • reset() - resets counter to 0
  • value() - returns current counter value without incrementing

Example:

const counter = makeCounter()
counter.increment() // 1
counter.increment() // 2
counter.value()    // 2
counter.reset()
counter.value()    // 0
πŸ’‘ Hints (2)
  • β€’ Return an object with multiple methods
  • β€’ All methods share the same closure variable