splice() Method in JavaScript

JavaScript2 min read
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 splice() 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 start-index.

Example:

We have a playlist array containing 6 songs:

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

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

playlist.forEach((item, index) => { document.write(index + " > " + item + "<br>"); }); // Output: 0 > song-1 1 > song-2 2 > song-3 3 > song-4 4 > song-5 5 > song-6

Removing an Element:

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

Adding an Element:

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

Displaying the Updated Playlist:

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

Summary:

  • The splice() 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.