Slice() and Splice() in JavaScript

The Array.Slice() and Array.Splice() are methods of the Array class, to manipulate arrays. Although they sound similar, these two methods work differently. Let us see an example which demonstrates how the two methods are different from each other

Slice() - Creates a new array from elements of an existing array. It does not modify the original array. The Slice() method takes two arguments. The first argument is an integer that specifies where to start the selection. The second argument is optional and is an integer that specifies where to end the selection.

Slice() Javascript

In the code shown above, slice() starts at position 1 and copies “two”, “three” into the new array (newArrSlice). The original array (nums) is not modified by the slice() method.

Slice() Javascript

Some important points about slice():

  • Index starts from zero
  • If a single argument is given to the slice() method, the array returned will contain all elements from the start position to the end of array.
  • If a negative value is supplied for either parameters, this means that the slice() will count the position from the end of the array, instead of the beginning. So in the above example, if we specify nums.splice(-1,-3), it will return “three” and “four”

Splice() – Deletes and/or inserts elements in an array. Unlike slice(), the splice() method modifies the original array and returns a new array. The Splice() method takes three arguments. The first parameter is the index to start deleting and/or insert elements, the second param is number of elements to remove and third param (optional) is the new elements to be added to the array.

Splice() Javascript

In the code shown above, the splice() method starts at position 2 i.e element “three” and removes a length of 2 elements i.e. removes element “three” and “four”.

Splice() Javascript

Some important points about splice():

  • Index starts from zero
  • If a single argument is given to the splice() method, all elements from the start index to the end of the array will be removed
  • If a negative value is supplied for the parameter, the elements are spliced from the end and not from the beginning of the array





About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

1 comment:

Unknown said...

good example thanks :)