Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Counter Sequence

A Closer Look at Functionsmedium

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

Implement `counterValues(n)` that builds a counter using a closure and returns the array of values it produces over `n` calls: `[1, 2, ..., n]`.

Sample tests

Input: counterValues(3)
Output: [1,2,3]
Input: counterValues(0)
Output: []

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Resetting the counter inside the loop, losing the closed-over state.

Learning resources

  • MDN: Closures
Approach & explanation (try first)

The inner function captures count by closure, so each call increments the same private variable, producing 1..n.

Loading...
⌘/Ctrl + Enter

Run your code to see results.