JavaScript Slice and Splice
slice and splice are two array methods that take items from an array. slice copies items out, and splice changes the array itself.
Slice a range
slice copies a range into a new array here. Both arrays log below, and the original keeps all four items.
const fruits = ["Apple", "Pear", "Plum", "Kiwi"];
const part = fruits.slice(1, 3);
console.log(part);
console.log(fruits);Splice items out
splice removes two items starting at index 1 here. The call returns the removed items, and both results log below.
const fruits = ["Apple", "Pear", "Plum", "Kiwi"];
const removed = fruits.splice(1, 2);
console.log(removed);
console.log(fruits);Splice an item in
This splice call removes zero items at index 1. The value "x" lands at that index instead.
const letters = ["a", "c"];
letters.splice(1, 0, "x");
console.log(letters);Example
const fruits = ["Apple", "Pear", "Plum", "Kiwi"];
const part = fruits.slice(1, 3);
console.log(part);
console.log(fruits);
const removed = fruits.splice(1, 2);
console.log(removed);
console.log(fruits);
fruits.splice(1, 0, "Mango");
console.log(fruits);Key points
- slice builds a new array from a range of items.
- slice leaves the original array whole and unchanged.
- The end index in slice names a stop point, and that item stays out.
- splice changes its array in place at a chosen index.
- The second number in splice counts the items to remove, and 0 removes none.
- Strings also have a slice method with the same name, taught in the Strings lessons.
In this example, slice copies the items at indexes 1 and 2 into part. The next line logs the original array, still whole with four items. The splice call then removes those two items and returns them, leaving Apple and Kiwi. A final splice call inserts Mango at index 1 without removing anything.
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
How does slice differ from splice?