Menu
Coddy logo textTech

Splice

Lesson 16 of 18 in Coddy's Array Methods in JavaScript course.

The splice() method is a mutating method that allows you to add, remove, or replace elements within an existing array. It's like a "multi-purpose tool" for modifying arrays in place.

  • Modifies the original array (be cautious!).
  • Takes three arguments: startIndex (where to start modifying), deleteCount (number of elements to remove), and optional elements to insert.
  • If deleteCount is 0, elements are inserted at startIndex without removing anything.
  • Negative values for startIndex are allowed and count from the end of the array.

Let's say you have a list of upcoming concerts (strings) in a city and you want to remove one and add another. Here's how splice() can help:

const concerts = ["Rock Band", "Pop Star", "Jazz Trio"];

// Remove "Pop Star" (startIndex = 1, deleteCount = 1) and insert "Folk Singer" at the same position
concerts.splice(1, 1, "Folk Singer");

console.log(concerts); // Output: ["Rock Band", "Folk Singer", "Jazz Trio"] (original modified)

In above example, The "Pop Star" concert is removed, and "Folk Singer" is inserted at index 1, modifying the original concerts array. console.log() displays the modified concerts array with the updated list.

challenge icon

Challenge

Easy

You have given an array numbers of numbers.

You have to write JavaScript code to remove the last three numbers from the numbers array and add the string values a, b, c.

Finally, log the updated array.

Try it yourself

let numbers = [ 99, 32, 43, 54, 100];

// Write code here

All lessons in Array Methods in JavaScript