Skip to the solution
EasyPhone Screen7 min read

How does Array.prototype.with() let you replace one array element immutably, and where would that pattern actually help?

1.1k views

The problem

Question presented to candidate: "How does Array.prototype.with() work, what does it return compared to something like arr[index] = value or splice, and when would you actually reach for it in real code?"

What a strong answer should cover:

  • with(index, value) returns a brand-new array with the element at index replaced by value; the original array is left completely unchanged, both its reference and its contents.
  • This contrasts with direct index assignment (arr[i] = value) and splice(), both of which mutate the original array in place and return either the removed elements (splice) or nothing meaningful.
  • with() supports negative indices, counting back from the end, the same way at() does.
  • An out-of-range index, positive or negative, throws a RangeError rather than silently no-op-ing or growing the array.
  • Real use case: state-management code (Redux reducers, React state updates) that must return a new reference so change detection works correctly -- with() replaces the "spread then mutate a nested array" pattern, which is a common source of accidental mutation bugs.

Clarifying questions expected:

  • "Is this specifically about the ES2023 change-array-by-copy methods, or should I compare it against the full set of array mutation methods too?"
  • "Should I talk through a concrete state-management bug this method avoids?"

Code / implementation expected: Yes -- a runnable comparison of with() against splice()-based mutation and a copy-then-assign approach, plus a demonstrated state-management bug it avoids.

  • es2023
  • tricky
  • real-world

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

7 min read Β· 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptArray.prototype.with(): immutable replacement vs splice/mutation, plus a real reducer bug (run directly)

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 4 of 165 in JavaScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextEasy

How does 'use strict' change what `this` refers to inside a regular function called without a receiver, compared to non-strict mode?

Continue