User Tools

Site Tools


Java Script Slice vs Splice methods


slice() method returns a shallow copy of a portion of an array into a new array object.

The original array is not modified.


array.slice(begin, end)

begin (optional): The starting index (inclusive). end (optional): The ending index (exclusive).

const numbers = [1, 2, 3, 4, 5];
const sliced = numbers.slice(1, 3);
console.log(sliced); // [2, 3]
console.log(numbers); // [1, 2, 3, 4, 5] (unchanged)


splice() method changes the content of an array by removing and/or adding elements.

The original array is modified.


array.splice(start, deleteCount, item1, item2, ...)

start: The index at which to start changing the array. deleteCount (optional): The number of elements to remove. item1, item2, … (optional): The elements to add to the array.

const numbers = [1, 2, 3, 4, 5];
const spliced = numbers.splice(1, 2, 'a', 'b');
console.log(spliced); // [2, 3]
console.log(numbers); // [1, 'a', 'b', 4, 5] (modified)


slice is used to extract parts of an array without modifying it, while splice can add, remove, or replace elements within the array, changing its content in the process.
java-script/slice-vs-splice-methods.txt · Last modified: 2023/08/11 17:03 by odefta