JavaScript .splice() method

There are many array methods in Javascript but the one with which I struggle the most is, .splice() method.

javascript Logo

So the other day, I came across a leet code problem, which asked me to manipulate an array without making a copy of it! I searched for methods and I remembered, that .splice() can be useful for this problem. So without wasting any time lets dive into the basics of .splice() method.

In the above example .splice() is taking two parameters:

  • The index number(the point at which we want to start deleting elements)
  • The second parameter is the number of elements we want to remove from an array.

Here we are giving .splice(), three parameters, the third parameter is optional. Recap:

  1. First parameter: Starting index, the point at which you want to delete things
  2. Second parameter: Number of elements, you want to remove from an array
  3. Third parameter: Optional, elements you want to add at a specified position

When you don’t want to delete anything, just add “0”, to the second parameter.

I hope this blog was helpful! Now go ahead and play around with .splice() until it is clear and also challenge yourself with a leet code problem: Move Zeros. Here is a pdf, which includes methods available in Javascript.

Coach @FlatironSchool

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store