Skip to main content

JavaScript Array splice Method (Live Playground)

The splice method in JavaScript is used to change the content of an array by removing, replacing, or adding elements.

Here's a simple example of removing elements:

let fruits = ['apple', 'banana', 'mango', 'orange', 'kiwi'];

fruits.splice(2, 1);

console.log(fruits);
// Expected output: ["apple", "banana", "orange", "kiwi"]
Live Playground, Try it Yourself

In this example, we have an array called fruits. We use the splice method to remove one element at the second index. The first parameter of the splice method is the starting index, and the second parameter is the number of elements to remove.

You can also use the splice method to add new elements:

let fruits = ['apple', 'banana', 'orange', 'kiwi'];

fruits.splice(2, 0, 'mango');

console.log(fruits);
// Expected output: ["apple", "banana", "mango", "orange", "kiwi"]
Live Playground, Try it Yourself

In this case, we're adding "mango" at the second index. The first two parameters are the same, but now we're adding a third parameter: the new element to insert.

It's important to note that the splice method modifies the original array.

In conclusion, the splice method is an incredibly flexible tool in JavaScript for modifying arrays by adding, removing, or replacing elements. It's part of the suite of JavaScript array methods that greatly simplifies working with arrays.

Practicing with splice on different arrays and parameters will help you get a solid understanding of how it works!