Question presented to candidate: "Two variables point at the same array -- a classic aliasing setup. If I call .reverse() on one of them, what happens to the other? How does .toReversed() avoid that problem entirely?"
What a strong answer should cover:
- Array.prototype.reverse() reverses the array in place and returns the SAME array reference it was called on -- so any other variable or object property that was aliased to that same array reference sees the reversal too, which is often an unintended side effect.
- Array.prototype.toReversed(), added in ES2023, computes the reversed order into a brand-new array and leaves the original completely untouched -- the source array and its length, order, and identity are all unaffected.
- The bug this solves is aliasing: two variables, or a variable and a value stored elsewhere like React state or a Redux store, can point at the exact same array object without that being obvious from the code -- mutating through one reference silently corrupts what the other reference sees.
- toReversed() always allocates a new array, which is a real cost (O(n) memory and time) compared to reverse(), which is O(n) time but no extra allocation -- worth naming as the actual tradeoff, not a free lunch.
- The naming convention -- a to-prefixed method paired with an in-place counterpart -- also applies to toSorted()/sort(), toSpliced()/splice(), and with()/index assignment, all from the same ES2023 proposal.
Clarifying questions expected:
- "Is the concern here specifically about a shared reference, like two variables or a value that got passed into two places, or about immutability as a general programming style?"
- "Does this need to run in an older environment where toReversed might not be available yet?"
Code / implementation expected: Yes -- a real, executed side-by-side comparison where a second variable is aliased to the same array, showing reverse() leaking the mutation through the alias while toReversed() leaves the alias untouched.