Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Shallow Copy with Spread

Behind the Scenesmedium

Course · Section 8: How JavaScript Works Behind the Scenes · Lecture 104: Object References in Practice (Shallow vs. Deep Copies)

Implement `copyWith(obj, key, value)` returning a shallow copy of `obj` with `key` set to `value`, without mutating the original.

Sample tests

Input: copyWith({"a":1}, "b", 2)
Output: {"a":1,"b":2}
Input: copyWith({"a":1}, "a", 9)
Output: {"a":9}

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • A shallow copy still shares nested objects with the original.
Visualize this concept: Primitives vs. References →
Approach & explanation (try first)

Spreading creates a new top-level object; nested values would still be shared references.

Loading...
⌘/Ctrl + Enter

Run your code to see results.