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: xxxxxxxxxx 1 slice() 2 slice(start) 3 slice(start, end) |
Syntax: xxxxxxxxxx 1 splice(start) 2 splice(start, deleteCount) 3 splice(start, deleteCount, item1) 4 splice(start, deleteCount, item1, item2, itemN) |
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. |
In this example, we present how slice()
and splice()
methods affect array.
xxxxxxxxxx
1
const array = ['a', 'b', 'c', 'd'];
2
3
console.log(array.slice(2)); // [c,d] (selected items)
4
console.log(array); // [a,b,c,d] (original array didn't change)
xxxxxxxxxx
1
const array = ['a', 'b', 'c', 'd'];
2
3
console.log(array.splice(2)); // [c,d] (removed items)
4
console.log(array); // [a,b] (original array changed)