EN
JavaScript - array slice() vs splice()
0
points
In this article, we would like to show you the difference between array slice() and splice() methods in JavaScript.
slice() | splice() |
|---|---|
slice() doesn't change the original array | splice() changes the original array |
|
Syntax:
|
Syntax:
|
slice() method returns the selected elements in an array, as a new array | splice() method returns items removed from an array |
slice() method without arguments can be used to copy the whole array | splice() method with three or more arguments can be used to remove some items and insert new ones. |
Practical examples
In this example, we present how slice() and splice() methods affect array.
1. slice()
// ONLINE-RUNNER:browser;
const array = ['a', 'b', 'c', 'd'];
console.log(array.slice(2)); // [c,d] (selected items)
console.log(array); // [a,b,c,d] (original array didn't change)
2. splice()
// ONLINE-RUNNER:browser;
const array = ['a', 'b', 'c', 'd'];
console.log(array.splice(2)); // [c,d] (removed items)
console.log(array); // [a,b] (original array changed)