Array Slice and Splice Methods
slice() and splice() have similar names but do different jobs. slice() copies part of an array into a new array and leaves the original alone. splice() changes the array it is called on, by removing elements, inserting them, or both, and returns the elements it removed.
slice(start, end) returns the elements from index start up to, but not including, index end. Leaving out end takes everything to the end of the array, and a negative index counts back from the end. With no arguments, slice() copies the whole array.
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'];
console.log(months.slice(1, 3));console.log(months.slice(3));console.log(months.slice(-2));console.log(months.slice());console.log(months);This prints:
[ 'Feb', 'Mar' ][ 'Apr', 'May', 'Jun' ][ 'May', 'Jun' ][ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun' ][ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun' ]The copy is shallow, so objects in it are shared with the original. Strings have a slice() method that works the same way on characters.
splice
Section titled “splice”splice(start, deleteCount, ...items) removes deleteCount elements starting at start, then inserts any items in their place. A deleteCount of 0 inserts without removing anything, and passing both removes and inserts at once, which replaces elements.
const queue = ['Asha', 'Tom', 'Mei', 'Raj'];
const removed = queue.splice(1, 2);console.log(removed);console.log(queue);
queue.splice(1, 0, 'Lena', 'Sam');console.log(queue);
queue.splice(-1, 1, 'Priya');console.log(queue);This prints:
[ 'Tom', 'Mei' ][ 'Asha', 'Raj' ][ 'Asha', 'Lena', 'Sam', 'Raj' ][ 'Asha', 'Lena', 'Sam', 'Priya' ]The return value is always an array of what was removed, so it is empty when deleteCount is 0. Leaving out deleteCount altogether removes everything from start to the end.
toSpliced
Section titled “toSpliced”toSpliced(), added in ES2023, takes the same arguments as splice() but returns a new array with the changes made and leaves the original as it was. Use it when other code still needs the original, for example when the array is part of an application’s state.
const playlist = ['Intro', 'Verse', 'Chorus', 'Outro'];
const edited = playlist.toSpliced(1, 1, 'Bridge');
console.log(edited);console.log(playlist);This prints:
[ 'Intro', 'Bridge', 'Chorus', 'Outro' ][ 'Intro', 'Verse', 'Chorus', 'Outro' ]Arrays with JavaScript covers adding and removing elements at the ends of an array, and Manipulating & Sorting Arrays has more on splice() alongside reversing and sorting.
Steve Griffith covers this topic in his video JS Array Slicing and Splicing.