2

Javascript cheat sheet: .slice() and .splice()

 1 year ago
source link: https://dev.to/babib/javascript-slice-and-splice-cheat-sheet-3hoi
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

I recently came across a twitter post where the user challenged others if they knew the difference between the js methods .slice() and .splice() without googling them. A lot of people mixed them up.

So I've created this simplified cheat sheet of everything you need to know about the 2 methods.

What you should know

  • .slice() and splice() are both array methods.

  • both of them return arrays as outputs

  • the key is to pay attention to what they return as the output array and if they mutate the original array (they one on which the were applied to)

    1) .slice()

  • .slice() returns selected elements in an array, as a new array. Selection is done by index.

  • .slice() does not affect the original array

With splice() you can select one or more elements.

For example: This code snippet returns 3 (which is at index 2)

[1,2,3,4,5].slice(2) // returns 3 (which is at index 2)

and this code snippet returns 2,3,4 (from index 1 to 4 exclusively)

[1,2,3,4,5].slice(1,4) // returns 2,3,4 (from index 1 to 4 exclusively)

2) .splice()

  • .splice modifies the original array (adds and/or removes elements from the array)

  • The method returns the original array **modified**

With splice you can:

  • remove elements
[1,2,3,4,5].splice(3) // returns [1,2,3] (first 3 elements)
[1,2,3,4,5].splice(2,2) // at position 2 remove 2 elements (returns [1,2,5])
  • add elements

[1,2,5].splice(2,0,3,4) // at postion 2 add 2 elements (returns [1,2,3,4,5])

  • remove and add elements at the same time
// at position 2, remove 1 elements and add 2 new items
[1,2,3,4,5].splice(2,2,"HTML","CSS") // returns [1,2,"HTML","CSS",5]

Remember: .splice() mutates the array, .slice() does not!

Hope this is helpful to someone 💜


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK