Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 51

Modifying Arrays with `splice()`

This lesson is built with resources from youtube.com, javascripttutorial.net and 1 more site.

Hello! Welcome back to our journey through JavaScript arrays.

In our last lesson, we explored slice(), a "non-destructive" method that allows us to create a copy of an array without changing the original. This is like taking a photo of a document—you get a copy, but the original remains untouched.

Today, we're diving into its powerful and deceptively similar-sounding cousin: splice(). The key difference to remember is that slice() reads, while splice() writes. splice() is a "destructive" or mutating method, meaning it directly modifies the original array. Think of it less like photography and more like surgery: you go in, remove parts, add new ones, and permanently alter the subject.

By the end of this lesson, you will be able to use the splice() method to expertly modify arrays by removing, adding, or replacing elements at any position. Mastering this is crucial for managing dynamic collections of data, a common task in any application.

The Anatomy of splice()

The splice() method is incredibly versatile, and its power comes from its parameters. The general syntax looks like this:

array.splice(start, deleteCount, item1, item2, ...)

Let's break this down:

  • start: The index where the modification begins. This is the only required parameter.
  • deleteCount (optional): An integer indicating the number of elements to remove from the start index.
  • item1, item2, ... (optional): The elements you want to add to the array, beginning from the start index.

A crucial concept to grasp is that splice() does two things simultaneously:

  1. It modifies the original array. This is its primary purpose.
  2. It returns a new array containing the elements that were deleted. If no elements are deleted, it returns an empty array [].

Let's explore the three main ways to use this powerful surgical tool.


1. Removing Elements

The most straightforward use of splice() is to remove elements from an array. To do this, you provide the start index and the deleteCount.

For a clear explanation with helpful visuals, let's turn to a great tutorial.

JavaScript Array splice(): Delete, Insert, and Replace Elements

The article 'JavaScript Array splice()' from javascripttutorial.net provides a fantastic breakdown of how to use this method for deletion. Pay close attention to the diagram illustrating the process.

Read the section 'Deleting elements using the splice() method'. Focus on the code example with the scores array and study the accompanying diagram. Notice what happens to the original scores array and what the deletedScores variable contains.

As the article explains, if we have an array let scores = [1, 2, 3, 4, 5]; and we run scores.splice(0, 3), we are telling JavaScript: "Starting at index 0, remove 3 elements."

The result is:

  • The scores array is permanently changed to [4, 5].
  • The splice() method returns a new array [1, 2, 3], which contains the elements that were removed.

Here's another great visual for this operation:

JavaScript Array splice() Method for Deletion
This diagram shows an array of letters. The operation `splice(0, 4)` starts at index 0 ('C') and removes 4 elements, leaving only ['N', 'G'] in the original array.
Test your understanding!

You are managing a playlist, represented by an array of song titles.

let playlist = ['Song A', 'Song B', 'Song C', 'Song D', 'Song E'];

You need to remove 'Song C' and 'Song D' from the playlist.

  1. Write the splice() command to remove these two songs.
  2. Store the removed songs in a new variable called removedSongs.
  3. Log both the updated playlist and the removedSongs to the console to verify your work.
Show answer
let playlist = ['Song A', 'Song B', 'Song C', 'Song D', 'Song E'];

// 1. 'Song C' is at index 2. We want to remove 2 songs from there.
const removedSongs = playlist.splice(2, 2);

// 3. Log the results
console.log(playlist);       // Expected output: ['Song A', 'Song B', 'Song E']
console.log(removedSongs);   // Expected output: ['Song C', 'Song D']

Explanation: playlist.splice(2, 2) tells JavaScript to go to index 2 (where 'Song C' is) and remove 2 elements. The original playlist array is modified, and the two removed songs are returned and stored in the removedSongs variable.


2. Adding Elements

You can also use splice() to add new elements without removing any. The trick is to set the deleteCount to 0.

The syntax becomes: array.splice(start, 0, item1, item2, ...)

This tells JavaScript: "Starting at the start index, remove 0 elements, and then insert these new items."

JavaScript Array splice(): Delete, Insert, and Replace Elements

Let's return to the same javascripttutorial.net article to see how insertion works. The diagrams here are again very helpful.

Read the section 'Inserting elements using the JavaScript Array splice() method'. Look at both examples: one for inserting a single element and one for inserting multiple. The diagrams clearly show how the existing elements are pushed aside to make room for the new ones.

Let's see it in practice. Suppose we have a list of colors and want to insert 'purple' in the middle.

const colors = ['red', 'green', 'blue'];

// Start at index 2, delete 0 elements, and add 'purple'
colors.splice(2, 0, 'purple');

console.log(colors); // Output: ['red', 'green', 'purple', 'blue']

Since we deleted 0 elements, the splice() method would return an empty array [].


3. Replacing Elements

The final and most comprehensive use of splice() is to replace elements. This is simply a combination of removing and adding. You specify a start index, a deleteCount greater than 0, and the new items to insert.

JavaScript Array .splice() Method for Replacing Elements
This visual perfectly demonstrates replacement. The operation starts at index 0, removes 2 items, and then inserts 2 new items in their place, directly modifying the array.

The number of elements you insert does not have to match the number you delete. This allows the array to grow or shrink.

JavaScript Array splice(): Delete, Insert, and Replace Elements

The final section of the javascripttutorial.net article covers this combined operation.

Read the section 'Replacing elements using the JavaScript Array splice() method'. Notice the two examples: the first replaces one element with one new element, and the second replaces one element with three new elements, causing the array to grow.

Let's replace 'C++' with 'Python' in a list of programming languages:

let languages = ['C', 'C++', 'Java', 'JavaScript'];

// Start at index 1, remove 1 element, and add 'Python'
let replaced = languages.splice(1, 1, 'Python');

console.log(languages); // Output: ['C', 'Python', 'Java', 'JavaScript']
console.log(replaced);  // Output: ['C++']

Video Walkthrough and Deeper Dive

Now that you have a solid grasp of the three main uses of splice(), let's watch a video that ties it all together. This video provides a great step-by-step walkthrough and also introduces how to use negative indices, which is a great "under the hood" detail to know.

Splice - Array Methods - Javascript Tutorial

The 'Splice - Array Methods' video by Web Dev Cody is an excellent, detailed tutorial. It breaks down each parameter and demonstrates its effect with clear examples.

Watch the entire video (around 8 minutes). Pay close attention to how he explains each parameter's role. Specifically, note the section on negative indices (around 02:28), which allows you to count from the end of the array. This is a very useful feature.


Conclusion

You have now learned how to perform surgical modifications on your arrays using splice(). Unlike its gentle cousin slice(), splice() is a powerful tool that directly alters your data.

Key Takeaways:

  • splice() is a mutating method; it changes the original array.
  • The syntax is array.splice(start, deleteCount, ...itemsToAdd).
  • It can be used to remove (by specifying start and deleteCount), add (by setting deleteCount to 0), or replace elements.
  • It always returns a new array containing any elements that were deleted.
  • Be careful when using splice()! Since it modifies your data directly, it can be the source of bugs if you're not aware of its behavior. It's the opposite of slice(), which provides a safe, non-destructive copy.

Next Up

So far, we've focused on methods for manually manipulating arrays by adding, removing, or extracting elements. In the next lesson, we will move on to one of the most common tasks in programming: iterating over an array to perform an action on each element. We'll start with the forEach method, which provides a clean and modern way to loop through your data.