How to Use Splice in JavaScript: Understanding the Array Method

Written by Iggy | Published 2022/12/08
Tech Story Tags: javascript | programming | javascript-arrays | blogging-fellowship | web-development | beginners-guide | learn-to-code-javascript | hackernoon-top-story | web-monetization | hackernoon-es | hackernoon-hi | hackernoon-zh | hackernoon-vi | hackernoon-fr | hackernoon-pt | hackernoon-ja

TLDRThe splice Javascript Array method mutates an array, hence it's not suitable for some operations especially when you don't need to change the data. via the TL;DR App

Splice is a Javascript Array method that changes the content of an array by deleting or replacing an existing element or adding a new element in place.

In this guide, I will explain how to use the Javascript Array splice method. Developers at any level can read and understand this article.


Understanding the Array Method(splice)

If we take a look at the MDN website we would realize that the Javascript array prototype constructor, which allows us to add new methods and properties to the Array() object has a lot of methods and splice is one of them.

Array.prototype.splice()

If we however tried to use this same method on the string prototype, like the example below;

const strings = 'learn'

strings.splice()

We would however receive, a type error saying:

Uncaught TypeError: strings.splice is not a function

It is important to know that splice and slice aren’t the same. The slice method doesn’t mutate or change your data but the splice method does and this is why the splice method can’t be used on strings: strings are immutable.


How to use the Javascript array splice method

Using the splice Javascript array method is easy, but the syntax is sometimes misused.

You can use the splice method in these steps

arr.splice(start, deleteCount, item1, ..., itemN)

The splice() property takes some parameters, these parameters are used to determine the behavior of whatever array the splice method’s been called upon.

They are as follows:

  • Start
  • deleteCount
  • Items

Start

This is just the index at which we want our array to start the change, no element will be removed if the element's index is greater than the array’s length. But it adds an argument to the end of the array if the index is less than the array’s length.

deleteCount

This is an optional parameter that denotes the number of elements to be removed from the array, to delete or remove an element the start parameter must be present.

If you don’t include this parameter, or if it has equal value to the array’s length or is even greater than the array’s length, all the elements from the start parameter to the last item in the array would be removed. Note, this parameter must be included if there’s an item parameter present.

Items

This is also an optional parameter that tells you the element to be added to the array

If we don’t state the elements, the Javascript array’s splice() method will delete elements from the array. This would return an empty array.


Use cases

Now that we have understood what the parameters are, let’s try to see use cases and examples of how this can be implemented when writing our program.

Deleting zero elements before a specified index

If we want to add an element without removing any item, we simply specify the index, and it would remove nothing but start before the specified index.

Let’s have a look at the example below:

const myMusic = ['piano', 'guitar', ‘violin', 'orchestra'];

const removedElement = myMusic.splice(2, 0, 'drum');

// myMusic is [piano', 'guitar', ‘drum’, ‘guitar’, ‘violin’, ‘orchestra’]

// removedElement is empty  [ ], no elements deleted

In the preceding code, we try to remove an element on index 3(mandarin), meaning as soon as it gets to index 3 whatever items it finds would be deleted without replacing it with any element.

We can also delete one element and add other elements.

const myMusic = ['piano', 'guitar', 'drum', 'violin', 'orchestra']

const removedElement = myMusic.splice(3, 1, ‘sax’);

// myMusic is  ['piano', 'guitar', 'drum', 'sax', 'orchestra']

// removedElement is ['violin']

Similarly, as soon as we got to index 3, whatever it finds, in this case, ‘orchestra’, would be deleted, and add newer ones (‘sax’), The code above shows how ‘drum’ was added to the array. Starting from index 2 the zero tells it to remove nothing, if we had 1 there it would remove 1 element and add the item we want, and so on.

Deleting one or more elements at a specified index

Say we wanted to remove one item or element without adding a new one into the array, we could just write it like the preceding code snippet

const myMusic = ['piano', 'guitar', 'drum', 'violin', 'orchestra'];

const removedElement = myMusic.splice(3, 1);

// myMusic is ['piano', 'guitar', 'drum', 'ochestra']

// removedElement is ['violin']

We can start at any index and remove as many items as we want.

Delete all elements beginning from a specified index

We can delete all elements in the array starting from whatever index we want. Let’s say, for example, we want to remove all starting from index 1. Once it gets to index 1, every element starting from index 1 would be deleted.

const myMusic = ['piano', 'guitar', 'drum', 'violin', 'orchestra']

const removedElement  = myMusic.splice(1);

// myMusic is  ['piano', 'guitar']

// removedElement is ['drum', 'sax', 'ochestra']

This code snippet tries to remove all elements starting from index 1. Where index 1 is ‘clown’ in the array. Since counting begins from 0, this would return a new array. that contains just one element which is ‘angel’. This is because during the counting ‘angel’ appears to be on index 0,.and counting begins at index 1. Index 0 would be omitted making it return that result.


Takeaways

If you need to perform a task on an array, and you don’t want the original array changed, the Javascript array’s splice() method should be avoided because they change your data.

const beforeSplice = ['bread','fish','cook']

console.log(beforeSplice)

//  ['bread', 'fish', 'cook']

const afterSpliceData = beforeSplice.splice(1)

console.log(afterSplice)

//  ['fish', 'cook']

In the example above. Before the splice Javascript array’s method was called on the beforeSplice variable. We had 3 elements, but after the method was applied, it returns 2 elements. This method has changed the data. Sometimes this isn’t what we want. But if all you simply want to do is remove elements or add an element, it’s perfect.

See you at the next one.


Written by Iggy | software developer || web development tutor @careerFoundry || Technical writer
Published by HackerNoon on 2022/12/08