Octagram Labs
JavaScriptData StructuresReact
Sign in
← Back to problems

Increment a Counter Field

Immutable Stateeasy

Course · Section 9: Data Structures, Modern Operators and Strings · Lecture 111: The Spread Operator (...)

Implement `incrementField(state, key)` returning a new object with the number at `key` increased by one.

Sample tests

Input: incrementField({"count":0}, "count")
Output: {"count":1}
Input: incrementField({"n":5}, "n")
Output: {"n":6}

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • state[key]++ mutates the object.
  • Calling the updater with a stale value when several increments happen in one render (prefer the functional updater in real React).

Learning resources

  • React: Updating Objects in State
Approach & explanation (try first)

Return a new object with the counter field increased by one, leaving the rest of state intact.

Loading...
⌘/Ctrl + Enter

Run your code to see results.