• Post category:JavaScript
  • Reading time:4 mins read

Today we will discuss about the Splice and Slice array methods in JavaScript with an example. The splice() and slice() both methods look similar, but act in very different ways.

Array Methods

  1. splice()
  2. slice()

1. splice()

The splice() array method adds or removes items from an array and returns an array with the removed items.

Syntax of the splice() method:

array.splice(index, removeCount, itemList)

Here, index argument is the start index of the array from where splice() will start removing the items. removeCount argument is the number of elements to delete starting from index and itemList is the list of new items which indicates the items to be added to the array.

var colours = ["Blue","Pink","White","Yellow"];
var newArray = colours.splice(2, 2, "Black", "Purple");
console.log(colours); //Output: ["Blue", "Pink", "Black", "Purple"]
console.log(newArray); // Output: ["White", "Yellow"]

There is no need to write second argument if we want to remove all the items from starting index to end of the array.

var colours = ["Blue","Pink","White","Yellow"];
var newArray = colours.splice(2);
console.log(colours); // Output: ["Blue", "Pink"]
console.log(newArray); // Output: ["White", "Yellow"]

This method can be used when we need to add one or more items into array in place of removed items, but it’s not necessary to replace all the items we removed.

2. slice()

The slice() method returns the selected item(s) of an array into a new array. It doesn’t modify the original array.

Syntax of the slice() method:

array.slice(startIndex, endIndex);

Here, the slice() method will select the item indexed by start argument and finish at the item indexed by end argument.

var colours = ["Blue","Pink","White","Yellow"];
var newAray = colours.slice(0, 2);
console.log(colours); //Output: ["Blue", "Pink", "Black", "Purple"]
console.log(newAray); // Output: ["Blue", "Pink"]

If you want to take any items from an array then you can use this method and it does not affect your existing array.

Thank you for reading. Happy Coding!

Leave a Reply