slice vs splice in JavaScript

Are you finding yourself always looking up the difference between slice() and splice()? Well, hereโ€™s a quick rundown of the difference.

TL;DR: slice is immutable and splice mutates the array.

Array.prototype.slice

The slice method returns a new array with a copied slice from the original array. The first optional argument is the beginning index and the second optional argument is the ending index (non-inclusive).

Without arguments, you get a copy of the full array:

const myArr = ['๐Ÿ•', '๐Ÿพ', '๐ŸŽŠ', 'โœจ'];

const myArrCopy = myArr.slice();

console.log(myArrCopy); // ["๐Ÿ•", "๐Ÿพ", "๐ŸŽŠ", "โœจ"]

With one argument, you get a copy from the specified index (zero-based) to the end of the array:

const myArr = ['๐Ÿ•', '๐Ÿพ', '๐ŸŽŠ', 'โœจ'];

const myArrCopy = myArr.slice(2);

console.log(myArrCopy); // ["๐ŸŽŠ", "โœจ"]

The specified beginning index can also be negative, in which case the starting index is calculated from the end:

const myArr = ['๐Ÿ•', '๐Ÿพ', '๐ŸŽŠ', 'โœจ'];

const myArrCopy = myArr.slice(-3);

console.log(myArrCopy); // ["๐Ÿพ", "๐ŸŽŠ", "โœจ"]

And then hereโ€™s an example with two argument provided:

const myArr = ['๐Ÿ•', '๐Ÿพ', '๐ŸŽŠ', 'โœจ'];

const myArrCopy = myArr.slice(-3, 2);

console.log(myArrCopy); // ["๐Ÿพ"]

Array.prototype.splice

The splice method changes the content of the array in place and can be used to add or remove items from the array.

When only one argument is provided, all the items after the provided starting index are removed from the array:

let myArr = ['๐Ÿ•', '๐Ÿพ', '๐ŸŽŠ', 'โœจ'];

myArr.splice(2);

console.log(myArr); // ["๐Ÿ•", "๐Ÿพ"]

The second optional argument is for the number of items to remove:

let myArr = ['๐Ÿ•', '๐Ÿพ', '๐ŸŽŠ', 'โœจ'];

myArr.splice(2, 1);

console.log(myArr); // ["๐Ÿ•", "๐Ÿพ", "โœจ"]

An arbitrary amount of additional arguments can be passed-in and will be added to the array:

let myArr = ['๐Ÿ•', '๐Ÿพ', '๐ŸŽŠ', 'โœจ'];

myArr.splice(2, 1, '๐ŸŒญ', '๐ŸŒฎ');

console.log(myArr); // ["๐Ÿ•", "๐Ÿพ", "๐ŸŒญ", "๐ŸŒฎ", "โœจ"]

You can specify 0 as the number of items to remove to simply add new items at the specified location in the array:

let myArr = ['๐Ÿ•', '๐Ÿพ', '๐ŸŽŠ', 'โœจ'];

myArr.splice(2, 0, '๐ŸŒญ', '๐ŸŒฎ');

console.log(myArr); // ["๐Ÿ•", "๐Ÿพ", "๐ŸŒญ", "๐ŸŒฎ", "๐ŸŽŠ", "โœจ"]
  Tweet It
✖ Clear

๐Ÿ•ต Search Results

๐Ÿ”Ž Searching...