JavaScript slice, splice, fill, copyWithin and the ES2023 Copying Methods (toSpliced, toSorted, with)
Working with parts of an array: slice to copy a range, splice to remove, insert and replace in place, fill and copyWithin, and the ES2023 non-mutating versions toSpliced, toSorted, toReversed and with. Includes pagination, chunking, moving items, and the slice vs splice interview question.
kvi5hnuCode Sprout team member6 min readOn this page
The methods in this article work on a range of an array: copy it, remove it, replace it, fill it. The most famous pair, slice and splice, differ by one letter and behave completely differently, a favorite interview question. ES2023 then added copying versions of the mutating methods, which modern code (especially React) uses all the time.

slice: copy a range
slice(start, end) returns a new array with the elements from start up to, but not including, end. The original isn't touched.
const days = ["mon", "tue", "wed", "thu", "fri"];
console.log(days.slice(1, 3)); // indexes 1 and 2
console.log(days.slice(2)); // from 2 to the end
console.log(days.slice(-2)); // the last two
console.log(days.slice(1, -1)); // drop the first and last
console.log(days.slice(3, 1)); // start after end: empty
console.log(days); // unchanged
[ 'tue', 'wed' ]
[ 'wed', 'thu', 'fri' ]
[ 'thu', 'fri' ]
[ 'tue', 'wed', 'thu' ]
[]
[ 'mon', 'tue', 'wed', 'thu', 'fri' ]
The rules, which also apply to fill, copyWithin and the string slice method:
- Negative positions count from the end:
-1islength - 1. - The end is exclusive, so
slice(a, b)hasb - aelements, andslice(0, n)gives the firstn. - A missing
endmeans "to the end";slice()with no arguments copies the whole array.
slice() makes a shallow copy (article 54): the new array is separate, but object elements are shared:
const players = [{ name: "Ana", score: 1 }];
const copy = players.slice();
copy[0].score = 99;
console.log(players[0].score, copy !== players);
99 true
Pagination with slice
const results = Array.from({ length: 8 }, (_, i) => `item${i + 1}`);
const pageSize = 3;
const page = (n) => results.slice((n - 1) * pageSize, n * pageSize);
console.log(page(1), page(3), page(4));
[ 'item1', 'item2', 'item3' ] [ 'item7', 'item8' ] []
An end past the array's length is fine: slice just stops at the end.
splice: remove, insert and replace in place
splice(start, deleteCount, ...items) modifies the array: it removes deleteCount elements starting at start, inserts items in their place, and returns an array of the removed elements. The elements after the change shift to stay contiguous, and length adjusts.
const tasks = ["plan", "write", "test", "ship", "rest"];
console.log(tasks.splice(1, 2), tasks); // remove 2 at index 1
const queue = ["a", "b", "c", "d"];
console.log(queue.splice(2), queue); // no count: remove to the end
const recent = ["a", "b", "c", "d"];
console.log(recent.splice(-2, 1), recent); // negative start counts from the end
[ 'write', 'test' ] [ 'plan', 'ship', 'rest' ]
[ 'c', 'd' ] [ 'a', 'b' ]
[ 'c' ] [ 'a', 'b', 'd' ]
const steps = ["start", "finish"];
console.log(steps.splice(1, 0, "middle", "almost"), steps); // delete 0: pure insert
const colors = ["red", "green", "blue"];
console.log(colors.splice(1, 1, "lime"), colors); // replace one element
const grid = [1, 2];
grid.splice(1, 0, [9, 9]); // arrays are inserted as-is
console.log(grid);
[] [ 'start', 'middle', 'almost', 'finish' ]
[ 'green' ] [ 'red', 'lime', 'blue' ]
[ 1, [ 9, 9 ], 2 ]
slice vs splice
slice(start, end) | splice(start, count, ...items) | |
|---|---|---|
| Changes the array? | no | yes |
| Second argument | end index (exclusive) | number of elements to remove |
| Returns | the copied range | the removed elements |
| Can insert? | no | yes |
A trick to remember: splice inserts (and has the extra letter because it does more).
Removing an item by value
splice needs an index, so combine it with indexOf or findIndex, and check for -1. splice(-1, 1) would otherwise remove the last element:
function removeValue(arr, value) {
const i = arr.indexOf(value);
if (i !== -1) arr.splice(i, 1);
return arr;
}
console.log(removeValue(["x", "y", "z"], "y"), removeValue(["x", "y"], "q"));
[ 'x', 'z' ] [ 'x', 'y' ]
To remove all matching values, arr.filter((v) => v !== value) is simpler, though it returns a new array. Calling splice inside a forward loop skips elements (article 56); if you must, loop backwards.
fill: set a range to one value
fill(value, start, end) sets every element in the range to value, in place, and returns the array:
console.log(new Array(4).fill(0));
console.log([1, 2, 3, 4].fill(9, 1));
console.log([1, 2, 3, 4, 5].fill(0, 1, -1));
[ 0, 0, 0, 0 ]
[ 1, 9, 9, 9 ]
[ 1, 0, 0, 0, 5 ]
As article 54 explained, fill puts the same value in every slot, so fill([]) or fill({}) shares one object. Use Array.from({ length: n }, () => []) for separate ones.
copyWithin: move a range inside the array
copyWithin(target, start, end) copies the elements from start to end over the positions starting at target, in place, without changing length. It's a low-level operation, mainly useful with typed arrays and binary data (part 11), and handles overlapping ranges correctly:
console.log([1, 2, 3, 4, 5].copyWithin(0, 3)); // copy [4, 5] to the start
console.log([1, 2, 3, 4, 5].copyWithin(2, 0, 2)); // copy [1, 2] to index 2
[ 4, 5, 3, 4, 5 ]
[ 1, 2, 1, 2, 5 ]
You'll rarely see it in application code.
The ES2023 copying methods
splice, sort, reverse and index assignment all modify the array. That's a problem whenever an array is shared: React and Redux state, function arguments, frozen data. ES2023 added a non-mutating version of each, which returns a changed copy:
| Mutating | Copying (ES2023) |
|---|---|
arr.splice(i, n, ...items) | arr.toSpliced(i, n, ...items) |
arr.sort(compare) | arr.toSorted(compare) |
arr.reverse() | arr.toReversed() |
arr[i] = value | arr.with(i, value) |
const scores = [30, 10, 20];
console.log(scores.toSorted((a, b) => a - b));
console.log(scores.toReversed());
console.log(scores.toSpliced(1, 1)); // remove index 1
console.log(scores.toSpliced(1, 0, 15)); // insert at index 1
console.log(scores.with(0, 35), scores.with(-1, 25));
console.log(scores); // never changed
[ 10, 20, 30 ]
[ 20, 10, 30 ]
[ 30, 20 ]
[ 30, 15, 10, 20 ]
[ 35, 10, 20 ] [ 30, 10, 25 ]
[ 30, 10, 20 ]
Details worth knowing:
toSplicedreturns the new array, not the removed elements assplicedoes.with(index, value)accepts negative indexes, likeat, and throws aRangeErrorfor an index outside the array; it can't grow the array.- They work on frozen arrays, since they never write to the original.
- They turn holes into
undefined, so the result is always dense. - Typed arrays have
toSorted,toReversedandwith, but nottoSpliced(typed arrays can't change length).
These methods are supported in all modern browsers (since 2023) and Node 20+. Before them, the idiom was to copy first: [...arr].sort(), arr.slice().reverse().
const todos = [
{ id: 1, text: "buy milk", done: false },
{ id: 2, text: "call Bo", done: false },
];
const i = todos.findIndex((t) => t.id === 2);
const updated = todos.with(i, { ...todos[i], done: true });
console.log(updated[1].done, todos[1].done, updated[0] === todos[0]);
true false true
Unchanged elements are shared between the old and new arrays, which is exactly what frameworks expect: only the changed item is a new object.
Practical recipes
const chunk = (arr, size) =>
Array.from({ length: Math.ceil(arr.length / size) }, (_, i) =>
arr.slice(i * size, i * size + size),
);
console.log(chunk([1, 2, 3, 4, 5], 2));
const move = (arr, from, to) => {
const copy = arr.slice();
const [item] = copy.splice(from, 1);
copy.splice(to, 0, item);
return copy;
};
console.log(move(["a", "b", "c", "d"], 0, 2));
[ [ 1, 2 ], [ 3, 4 ], [ 5 ] ]
[ 'b', 'c', 'a', 'd' ]
move is how drag-and-drop reordering is usually implemented.
Common questions
How do I insert an element at a specific index?
In place: arr.splice(i, 0, item). As a copy: arr.toSpliced(i, 0, item) or [...arr.slice(0, i), item, ...arr.slice(i)].
How do I replace the element at index i without mutating?
arr.with(i, newValue). Before ES2023: arr.map((v, j) => (j === i ? newValue : v)).
Why does arr.splice(arr.indexOf(x), 1) sometimes delete the wrong element?
When x isn't in the array, indexOf returns -1, and splice(-1, 1) removes the last element. Always check for -1 first.
Are slice and the copying methods slow because they copy?
Copying is O(n), but it's fast native code. For typical UI-sized arrays it's negligible. In tight loops over large arrays, mutating a local array you own is fine.
Summary
slice(start, end)copies a range into a new array; end is exclusive, negatives count from the end, andslice()copies everything (shallowly).splice(start, count, ...items)removes, inserts or replaces in place and returns the removed elements.- Check
indexOffor -1 before splicing; remove all matches withfilter. fillsets a range to one value (one shared value);copyWithinmoves a range inside the array.- ES2023's
toSpliced,toSorted,toReversedandwith(i, v)return modified copies and leave the original alone: ideal for shared and immutable data.
Practice Questions
What does this print?
const a = [1, 2, 3, 4, 5];
const b = a.slice(1, 4);
const c = a.splice(1, 2);
console.log(a, b, c);
Answer
[ 1, 4, 5 ] [ 2, 3, 4 ] [ 2, 3 ]. slice copies indexes 1 to 3 without changing a; splice then removes two elements at index 1 from a and returns them.
What does this code return, and what would splice with the same arguments return?
["a", "b", "c"].toSpliced(1, 1, "x", "y")
Answer
toSpliced returns the new array [ 'a', 'x', 'y', 'c' ]. splice would return the removed elements, [ 'b' ], and change the original into [ 'a', 'x', 'y', 'c' ].
Write insertAt(arr, index, ...items) that returns a new array without mutating the input.
Answer
const insertAt = (arr, index, ...items) => arr.toSpliced(index, 0, ...items);
What does [1, 2, 3].with(3, 4) do?
Answer
It throws a RangeError: with only replaces existing indexes and can't append. Use [...arr, 4] to add.
Previous: JavaScript Stacks, Queues and Flattening: push, pop, shift, unshift, concat, flat and flatMap
Next: Sorting JavaScript Arrays: sort, Comparators, localeCompare, Stable Sort, reverse and toSorted

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.