JS Shorts: Array.splice() vs Array.slice()

JS Shorts: Array.splice() vs Array.slice()

Divine Orji's photo
Divine Orji
·Jan 8, 2022·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Table of contents

  • Array.splice()
  • Array.slice()
  • Further reading:

These two array methods can be difficult to differentiate due to spelling similarities and because they are both used to get chunks of an array. Let's check them out 🚀


Array.splice()

🗝Key things to note:

  • This JavaScript method is used to add elements to, remove elements from, or replace elements in an array.
  • This method modifies the existing array.
  • It takes in 3 major parameters: startIndex, deleteCount(optional), and newElement(optional).
  • startIndex indicates which index of the array to start from.
  • deleteCount indicates how many elements should be removed from the array.
  • newElement contains any element that should be added to the array at the startIndex point. There can be multiple newElements in a splice method.

💻Some examples:

Our initial array:

gadgets array

Example 1:

example one

Example 2:

example two

Example 3:

example three


Array.slice()

🗝Key things to note:

  • This JavaScript method is used to copy a specific range of elements from an array.
  • The original array remains the same. It doesn't get modified.
  • The slice() method stores the copied elements in a new array.
  • It takes in two parameters: startIndex(optional) and endIndex(optional).
  • startIndex indicates which index of the array to start from.
  • endIndex indicates which index of the array to stop at.
  • Array.slice() will copy the range of elements from the startIndex to the endIndex, except the element in the endIndex. (I'll explain this with an example 😅)

💻Some examples:

Our initial array:

grocery.png

Example 1:

protein.png Here, we copied out a range of elements from grocery and stored it in a new array named protein. Our startIndex is 2 ('eggs') and our endIndex is 5 ('onions'). This will return all the elements from 'eggs' to 'onions', except 'onions'.

Example 2:

leaveTomatoes.png If you specify only the startIndex, it will copy all the elements from that startIndex till the end of the array.

Example 3:

lastThree.png If your startIndex is negative, it will count backward from the end of the array, and copy the last n number of elements.


Further reading:

 
Share this