Skip to content

JavaScript slice vs splice

  • by

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:

JavaScript slice vs splice

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 Comparisonsplice() methodslice() method
ReturnsThe removed item(s) in an arrayThe selected element(s) in an array, as a new array object
Modifies original arrayYesNo
ArgumentsCan take n number of argumentsTakes 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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading