JavaScript Copying Array Methods: toSorted and with
Quick answer
Copying array methods return a changed array without changing the receiver. They include toSorted, toReversed, toSpliced and with.
How it works
toSorted(compare) sorts a new array; toReversed() reverses a copy; toSpliced(start, deleteCount, ...items) edits a copy; with(index,value) replaces one position in a copy. Negative with indices count from the end; out-of-range indices throw RangeError. Ordinary holes are read as undefined. These methods are shallow and require runtime support.
const a = [3, 1, 2];console.log(a.toSorted((x,y)=>x-y).join(","), a.join(","));Expected output in Node.js:
1,2,3 3,1,2Sorting the copy preserves the source.
const a = [4, 5, 6];console.log(a.with(-1, 9).join(","), a.toSpliced(1,1,8).join(","));Expected output in Node.js:
4,5,9 4,8,6Both operations start from the unchanged original.
Common mistakes
Unlike splice, toSpliced returns the edited array, not removed elements. For older runtimes use an appropriate shallow copy plus a mutating method after feature detection.
Practice
Replace a final score using with, then verify that the original last value remains.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Copying Array Methods: toSorted and with — Knowledge Check
Apply the taught concept and predict the output.
What happens when with receives an index beyond the array length?
Which method returns the entire edited copy after insertion and removal?
Do these copying methods recursively clone nested records?
What is the exact console output in JavaScript Copying Array Methods: toSorted and with example 1?
const a = [3, 1, 2];console.log(a.toSorted((x,y)=>x-y).join(","), a.join(","));What is the exact console output in JavaScript Copying Array Methods: toSorted and with example 2?
const a = [4, 5, 6];console.log(a.with(-1, 9).join(","), a.toSpliced(1,1,8).join(","));