JavaScript Array slice vs splice

In this post, we'll learn the difference between the JavaScript array methods slice()
and splice()
and when it's appropriate to use one over the other.
The difference between slice
and splice
is that slice
is immutable whereas splice
will mutate the array.
slice
The slice
method will take an array and return a new array with the elements specified by the optional start
and end
parameters.
They're both optional so if you leave both blank, it will return the entire array.
const array = [1, 2, 3, 4, 5];
const newArray = array.slice();
console.log(newArray); // [1, 2, 3, 4, 5]
If you provide the start
parameter, it will start at that index and go until the end of the array.
const array = [1, 2, 3, 4, 5];
const newArray = array.slice(2);
console.log(newArray); // [3, 4, 5]
The start
parameter can be negative to start at the end of the array.
const array = [1, 2, 3, 4, 5];
const newArray = array.slice(-2);
console.log(newArray); // [4, 5]
When you provide both the start
and end
parameters, it will return the elements between those two indexes.
const array = [1, 2, 3, 4, 5];
const newArray = array.slice(1, 3);
console.log(newArray); // [2, 3]
splice
The splice
method will directly modified the array, essentially adding or removing elements from it using the optional start
and count
parameters.
When you only provide the start
parameter, it will remove all elements from that index to the end of the array.
const array = [1, 2, 3, 4, 5];
array.splice(2);
console.log(array); // [1, 2]
When you provide both the start
and count
parameters, it will remove count
number of elements, starting at the start
index.
const array = [1, 2, 3, 4, 5];
array.splice(1, 2);
console.log(array); // [1, 4, 5]
You can pass an unlimited number of parameters to the splice
method. Every parameter after the count
parameter will be added to the array.
const array = [1, 2, 3, 4, 5];
array.splice(1, 2, "a", "b", "c");
console.log(array); // [1, "a", "b", "c", 4, 5]
This means that you can set count
to 0
with additional parameters to add to the array.
const array = [1, 2, 3, 4, 5];
array.splice(1, 0, "a", "b", "c");
console.log(array); // [1, "a", "b", "c", 2, 3, 4, 5]
Conclusion
Hopefully this post has helped you understand the difference between JavaScript array's slice
and splice
methods and how they work. Remember, the slice
method is immutable and the splice
method is mutable.
Resources
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!
Leave us a message!