Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Counter via Closure

A Closer Look at Functionsmedium

Course · Section 10: A Closer Look at Functions · Lecture 144: Closures

Implement `runCounter(start, times)` that creates an internal counter starting at `start`, calls the increment function `times` times, and returns the final counter value. (This exercises building and using a closure internally.)

Sample tests

Input: runCounter(0, 3)
Output: 3
Input: runCounter(5, 2)
Output: 7

+ 2 hidden tests run on Submit.

Hints

Common pitfalls
  • Declaring the counter where it resets each call loses the closed-over state.

Learning resources

  • MDN: Closures
Approach & explanation (try first)

The inner function captures a private counter by closure, so repeated calls advance the same state.

Loading...
⌘/Ctrl + Enter

Run your code to see results.