JavaScript’s slice() and splice() methods operate on arrays but have different functionalities. Understanding the differences between these methods is crucial for effective array manipulation in JavaScript.
While both methods return array objects, splice() modifies the original array, whereas slice() does not. The slice() method returns a shallow copy of a portion of an array.
array.slice(start, end)
The splice() method modifies the contents of an array by removing or replacing existing elements and/or adding new elements.
array.splice(start, deleteCount, newElem1, newElem2, ..., newElemN);
JavaScript slice vs splice examples
Simple example code.
<!DOCTYPE html>
<html>
<body>
<script>
const arr = [1, 2, 3, 4, 5];
// slice() method
const slicedArr = arr.slice(2, 4);
console.log(slicedArr);
console.log(arr);
// splice() method
const splicedArr = arr.splice(2, 2, 'a', 'b');
console.log(splicedArr);
console.log(arr);
</script>
</body>
</html>
Output:
Above example, The original array is not modified by the slice() method but The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements.
Feature Comparison | splice() method | slice() method |
---|---|---|
Returns | The removed item(s) in an array | The selected element(s) in an array, as a new array object |
Modifies original array | Yes | No |
Arguments | Can take n number of arguments | Takes 2 arguments (start index and end index) |
Comment if you have any doubts or suggestions on this JS method difference topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version