Question presented to candidate: "If you call arr.slice(1, 3) versus arr.splice(1, 2) on the same array, what happens to the ORIGINAL array in each case? Are the return values similar too?"
What a strong answer should cover:
- 📌 Interview term:
slice(start, end)— returns a new array containing a shallow copy of the specified portion, without mutating the original array at all. - 📌 Interview term:
splice(start, deleteCount, ...items)— mutates the original array in place, removingdeleteCountelements starting atstart, optionally inserting newitemsthere, and returns a new array of the elements that were removed. - 📌 Interview term: the real, direct answer to the prompt — verified directly: after
arr.slice(1, 3), the original array was genuinely completely unchanged; after the same-shapedarr.splice(1, 2), the original array was genuinely mutated — the two elements were removed in place, shifting the remaining elements down.slice's return value is the extracted portion;splice's return value is also the extracted portion, but the ORIGINAL array itself is left different afterward. - A precise answer names
splice's dual/triple capability, verified directly: passing0asdeleteCountwith additional items makes it insert-only (nothing removed); passing a non-zerodeleteCountalongside new items makes it replace elements in place. - A precise answer names that
splicehas no string equivalent — verified directly,typeof "hello".spliceis genuinelyundefined— since strings are immutable andsplice's entire purpose is in-place mutation;sliceworks identically on both arrays and strings, since it never needs to mutate anything.
Clarifying questions expected:
- None — this is a definitional/comparison question; directly answering the prompt's own mutation question for both methods is the strong signal.
Code / implementation expected: Yes — the before/after array comparison for both methods on identically-shaped calls is the clearest, most convincing demonstration.