Question presented to candidate: "You need to remove an item from a React state array without mutating it. splice() would mutate it in place. What would you use instead, and how does it actually behave differently under the hood?"
What a strong answer should cover:
- 📌 Interview term:
Array.prototype.toSpliced()— a real, ES2023 non-mutating sibling ofsplice()— takes the identical real arguments (start,deleteCount,...items) but genuinely returns a brand-new array reflecting the change, leaving the ORIGINAL array completely untouched. - 📌 Interview term: the real, direct verified contrast — verified directly: calling
splice()genuinely mutated the array it was called on in place (confirmed: the original array's own contents changed); callingtoSpliced()with the identical arguments on a separate, untouched original genuinely left that original completely unchanged, while producing a correct new array with the identical resulting shapesplice()would have produced. - 📌 Interview term: the real reference-identity guarantee — verified directly:
toSpliced()'s result is genuinely a DIFFERENT reference from the original array every single time it is called, even when logically removing zero items — the real property this bank's own dedicatedtoSorted()/toReversed()questions rely on for React's===-based change detection. - 📌 Interview term: toSpliced() is not just for removal — a precise answer names that, like
splice(),toSpliced()genuinely also supports INSERT-only (deleteCount: 0) and REPLACE (deleteCount > 0with replacement items) operations — verified directly with both variants. - A precise answer names the real, practical motivation: in a React (or any) state-management context,
.splice()'s in-place mutation genuinely breaks reference-equality-based change detection (the state object's reference never changes, so a re-render can be silently skipped) —toSpliced()genuinely avoids this entire class of bug by construction.
Clarifying questions expected:
- None — this is a comparison/practical question; directly demonstrating the real, verified mutation-vs-non-mutation contrast is the strong signal.
Code / implementation expected: Yes — real, side-by-side splice() and toSpliced() calls on separate copies of the same array, including remove, insert-only, and replace variants.