Copy Methods Return Fresh Arrays toSorted toReversed
toSorted, toReversed, toSpliced and with return new arrays and leave the source intact, replacing the mutate-then-clone pattern around shared state.
Code
// Array methods mutate in place; their copies are for pipelines that must not.
const base = [3, 1, 4, 1, 5];
// sort with a numeric comparator sorts ascending; without one it compares as strings
console.log("sorted copy:", base.toSorted((a, b) => a - b));
console.log("base intact:", base);
// reverse has a copying twin; splice's twin is toSpliced
console.log("reversed copy:", base.toReversed());
console.log("spliced copy:", base.toSpliced(1, 2, 9));
console.log("base still intact:", base);
// with() replaces one index and returns a fresh array
console.log("with(0, 99):", base.with(0, 99));
// fill mutates in place, so clone first when the source must survive
const padded = structuredClone(base);
padded.fill(0, 2);
console.log("filled clone:", padded, "source:", base);
// flat/flatMap never mutate: they always allocate a new array
console.log("flat:", [1, [2, [3]]].flat(2));
console.log("flatMap:", ["a,b", "c"].flatMap((s) => s.split(",")));Output
Captured from a sandboxed run of this snippet in the build pipeline.
sorted copy: [ 1, 1, 3, 4, 5 ]
base intact: [ 3, 1, 4, 1, 5 ]
reversed copy: [ 5, 1, 4, 1, 3 ]
spliced copy: [ 3, 9, 1, 5 ]
base still intact: [ 3, 1, 4, 1, 5 ]
with(0, 99): [ 99, 1, 4, 1, 5 ]
filled clone: [ 3, 1, 0, 0, 0 ] source: [ 3, 1, 4, 1, 5 ]
flat: [ 1, 2, 3 ]
flatMap: [ 'a', 'b', 'c' ]How it works
Module-level bindings hold the data — base, padded — with no function scope in between.
Applying it
Each run prints the 9 labeled blocks sorted copy:, base intact:, reversed copy:, spliced copy:, base still intact:, with(0, 99):, filled clone:, flat:, flatMap: in source order.
Statements that matter
const padded = structuredClone(base);
Interactive Tools for This Topic
FAQ
- Does it depend on any third-party library?
- No third-party library is referenced; the standard library covers it. Its state lives in module-level bindings: `base`, `padded`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.