slice() method returns a shallow copy of a portion of an array into a new array object.
Syntax:
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.
Syntax:
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)