Slice and splice in JavaScript arrays

Slice and Splice are one of the confusing concept related to JavaScript arrays. Many developers got confused with them.

So in this blog, I will be talking about the differences between them and technique using which you won’t get confused anymore.

Splice: 

  1. Returns the removed items. 
  2. Changes the original array. 
  3. Accepts 3 arguments:
    1. Index: required
    2. Count: optional – Num of items to be removed from the index. If not given all the items starting from the index till the end will be removed.
    3. New items to be added: optional

Uses:

It can be used to remove and add items to an array.

Examples:

Remove all items with Index argument only-
Remove selected items with Index and Count arguments-

If the Count argument-

  1. Not provided, then by default all the items would be removed starting from Index argument.
  2. Value is less than 0, then no item would be removed and array remains as it is.
Remove selected items and add new items with Index, Count and new items arguments-

Slice: 

  1. Returns the selected items as this method does not remove and changes the original array. 
  2. Does not changes the original array. 
  3. 2 arguments 
    1. Start index: required – included
    2. End index: optional – not included, if not given all the items from start index till the end will be removed.

Uses:

It can also be used to copy one array to another.

Examples:

With Start index argument only-

Returns the selected items starting from start index as and does not changes the original array

With start index and end index arguments-

Slice() will select value starting from start index till end index and value at end index will not be included.

Positive end index

Negative end index

If you give a negative end index value, then JS will start counting from the end. In this case, we have provided an end index = -3

  1. Value 5 (4th index will be considered as 1 value)
  2. Value 4 (3rd index will be considered as 2 value)
  3. Value 3 (2nd index will be considered as 3 value)

So slice method will select value between index 1 and 2, therefore the output is 2.

Now, if you see, the difference between them is not much and they also sound almost the same which in turn increases the confusion.

Technique

You can remember them by their literal meaning.

Slice can be defined as a small piece cut from the large portion. So in JS also slice returns the selected items from a large array.

Splice can be defined as a join between two ropes. So in JS, you can use splice to join two arrays at a defined index.


Thank you for reading 🙂

https://www.abstractapi.com?verify_gp=dBHdT25546d788

Leave a Reply