splice() Method in JavaScript

JavaScript
splice() Method in JavaScript
javascriptsplice methodarray methods

The splice() method is a built-in method in JavaScript that allows us to modify the original array by adding, removing, or replacing elements at a specific index.

splice() Method in JavaScript

The splice() method is a built-in method in JavaScript that allows us to modify the original array by adding, removing, or replacing elements at a specific index.

  • It directly modifies the original array.
  • It returns a new array containing the removed elements (if any).

The method takes up to three parameters:

  1. start-index: The position in the array where changes begin.
  2. number-of-elements-to-remove: The number of elements to remove from the array.
  3. new-element(s): Optional elements to add to the array at the .

Example:

We have a playlist array containing 6 songs:

1let playlist = ['song-1', 'song-2', 'song-3', 'song-4', 'song-5', 'song-6'];

To display all the songs with their index, we use the method:

1playlist.forEach((item, index) => {
2    document.write(index + " > " + item + "<br>");
3});
4
5
6
7// Output:
80 > song-1
91 > song-2
102 > song-3
113 > song-4
124 > song-5
135 > song-6

Removing an Element:

  • To remove the song at index , we use the method:
1playlist.splice(2, 1);  // Removes 'song-3'
  • After removing the song at index 2, the updated playlist becomes:
1['song-1', 'song-2', 'song-4', 'song-5', 'song-6']

Adding an Element:

  • Now, let's add a new song, , at index without removing any songs (hence, the second argument is ):
1playlist.splice(4, 0, 'song-7');  // Adds 'song-7' at index 4
  • The updated playlist becomes:
1['song-1', 'song-2', 'song-4', 'song-5', 'song-7', 'song-6']

Displaying the Updated Playlist:

  • Using again to show the modified playlist:
1playlist.forEach((item, index) => {
2    document.write(index + " > " + item + "<br>");
3});
4
5
6
7// Output:
80 > song-1
91 > song-2
102 > song-4
113 > song-5
124 > song-7
135 > song-6

Summary:

  • The method in JavaScript modifies the original array by adding, removing, or replacing elements.
  • It can take up to three parameters: the starting index, the number of elements to remove, and optional elements to add.
  • It returns a new array containing the removed elements, if any.