The array in JavaScript is one of the most widely used data structures and array methods allow for a variety of data manipulation libraries. When you first start JavaScript it may be difficult to know the difference between slice() and splice().
- Slice
The slice method takes an array and returns a new array with the elements specified by the optional start and end parameters.
It does not modify or change the original array. Instead, it creates a new shallow copy of the original array.
// No arguments
array.slice();
// One argument
array.slice(startIndex);
// Two arguments
array.slice(startIndex, endIndex);
Slice takes two optional arguments called: startIndex and endIndex.
If you do not pass any arguments, the entire original array will be copied by default.
Parameters
- startIndex
- The index where the slice should begin
- If the value is omitted, it will start at 0.
- endIndex
- The slice will end before this index.
- Splice
Unlike slice, spice is destructive — meaning that it alters the contents of the array. Splice can delete, replace existing elements, or add new elements an array. Splice alters the existing array, but it will return the removed items in an array.
let num = ['zero', 'one', 'two', 'three', 'four','five','six'];
console.log(num.splice(2));
// Output: ['zero','one']