Array.splice() methods both allow you to extract elements from an array, but they have some important differences in how they behave.
- Returns a new array containing the extracted elements.
- Does not modify the original array.
start (optional): The index at which to begin extraction (inclusive). If omitted, it starts from index 0.
end (optional): The index at which to stop extraction (exclusive). If omitted, it extracts until the end of the array.
- The extracted elements are shallow-copied to the new array. Any modifications made to the new array or its elements do not affect the original array.
1 2 3 4 5 6
const fruits = ['apple', 'banana', 'cherry', 'date']; const extracted = fruits.slice(1, 3); console.log(extracted); // ['banana', 'cherry'] console.log(fruits); // ['apple', 'banana', 'cherry', 'date']
array.splice(start, deleteCount, item1, item2, ...)
- Modifies the original array by removing or replacing elements.
- Returns an array containing the removed elements.
start: The index at which to start modifying the array.
deleteCount (optional): The number of elements to remove. If set to 0, no elements are removed.
item1, item2, ... (optional): Elements to insert at the
- The elements removed from the original array are returned as a new array.
deleteCount is 0, no elements are removed, and the new elements are inserted at the specified index.
1 2 3 4 5 6
const fruits = ['apple', 'banana', 'cherry', 'date']; const removed = fruits.splice(1, 2, 'orange', 'kiwi'); console.log(removed); // ['banana', 'cherry'] console.log(fruits); // ['apple', 'orange', 'kiwi', 'date']
Array.splice() can also be used to insert elements without removing any by setting
deleteCount to 0.
Array.slice() is used to create a new array containing a portion of the original array, while
Array.splice() modifies the original array by removing or replacing elements and returns the removed elements. Depending on your use case, you can choose the method that best suits your needs.