Splice and Slice array methods in JavaScript

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

Splice and Slice array methods in JavaScript, JavaScript Array splice vs slice, JavaScript Array.splice() vs Array.slice(), JavaScript Array splice() Method, JavaScript Array slice() Method, splice( ), & split( ) methods in JavaScript, Array slice vs splice in JavaScript, Array.prototype.slice(), Array.prototype.splice(), javascript array methods, The slice Method for JavaScript Arrays, How to use splice and slice methods in javascript.

Array Methods

  1. splice()
  2. slice()

Method 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:

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.

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

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.

Method 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:

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

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

That’s it for today.

Thank you for reading. Happy Coding!

If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *