Understanding Array.splice() in JavaScript

Jun 21, 2019

The Array#splice() function lets you modify an array in-place by adding and removing elements. It is most commonly used to remove elements from an array, but it can also be used to add elements to the middle of an array.

Remove Elements

The splice() function is the only native array function that lets you remove elements from the middle of the array without creating a new array. For example, suppose you had an array ['a', 'b', 'c', 'd']. Here's how you would remove 'c' using splice():

const arr = ['a', 'b', 'c', 'd'];

// Remove 1 element starting at index 2
arr.splice(2, 1);

arr; // ['a', 'b', 'd']

The first 2 parameters to splice() are called start and deleteCount. The start parameter tells splice() where to start modifying the array. The deleteCount parameter tells splice() how many elements to delete.

You may see JavaScript projects use filter() instead of splice() to remove elements from an array. The key difference between these two approaches is that filter() creates a new array. This means filter() is the better choice for applications that rely on immutability, like React apps.

const arr = ['a', 'b', 'c', 'd'];

// Remove 1 element starting at index 2
const arr2 = arr.filter((v, i) => i !== 2);

// `arr` still has 'c', because `filter()` doesn't modify the array
// in place. On the other hand, `splice()` modifies the array in place.
arr; // ['a', 'b', 'c', 'd']
arr2; // ['a', 'b', 'd']
arr2 === arr; // false

Adding Elements to the Middle

The splice() function also lets you add elements to the middle of the array. JavaScript arrays have a push() function that lets you add elements to the end of the array, and an unshift() function that lets you add elements to the beginning of the array. The splice() function is the only native array function that lets you add elements to the middle of an array.

For example, suppose you have an array ['a', 'b', 'd'] and you want to add 'c' after 'b'. Every parameter to splice() after the deleteCount parameter is treated as an element to add to the array at the startIndex. So to insert 'c', you call splice() with a deleteCount of 0 and 'c' as the third parameter.

const arr = ['a', 'b', 'd'];

let start = 2;
let deleteCount = 0;
arr.splice(start, deleteCount, 'c');

arr; // ['a', 'b', 'c', 'd'];

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Fundamentals Tutorials

×
Mastering JS
Hi, I'm a JavaScript programming bot. Ask me something about JavaScript!