JavaScript Array slice() method


The slice() method in JavaScript is used to extract a portion of an array and return it as a new array without modifying the original array. The method selects elements from the start index up to, but not including, the end index.

Syntax:

array.slice(start, end)
  • start (optional): The index at which to start extracting elements. If omitted, extraction starts from index 0.
  • end (optional): The index before which to end extraction (not included). If omitted, extraction continues to the end of the array.

Return Value:

  • A new array containing the extracted elements.

Key Points:

  • Does not modify the original array: slice() returns a new array and does not affect the original array.
  • Start is inclusive and end is exclusive: The element at the start index is included in the result, but the element at the end index is not.
  • Handles negative indices: Negative indices can be used to count elements from the end of the array.

Example 1: Basic usage

let fruits = ['apple', 'banana', 'orange', 'mango', 'kiwi']; let sliced = fruits.slice(1, 4); console.log(sliced); // ['banana', 'orange', 'mango'] console.log(fruits); // ['apple', 'banana', 'orange', 'mango', 'kiwi'] (original array unchanged)

In this example, the slice starts at index 1 and ends at index 4 (exclusive), so it extracts elements at indices 1, 2, and 3.

Example 2: Omitting the end parameter

let fruits = ['apple', 'banana', 'orange', 'mango', 'kiwi']; let sliced = fruits.slice(2); console.log(sliced); // ['orange', 'mango', 'kiwi']

If you omit the end parameter, slice() extracts all elements starting from the start index to the end of the array.

Example 3: Using negative indices

let fruits = ['apple', 'banana', 'orange', 'mango', 'kiwi']; let sliced = fruits.slice(-3, -1); console.log(sliced); // ['orange', 'mango']

Negative indices count from the end of the array:

  • -3 refers to the third-to-last element (orange).
  • -1 refers to the last element but is excluded.

Example 4: Copying an entire array

let fruits = ['apple', 'banana', 'orange']; let copiedArray = fruits.slice(); console.log(copiedArray); // ['apple', 'banana', 'orange'] console.log(fruits === copiedArray); // false (they are different arrays)

By calling slice() without any arguments, you can create a shallow copy of the array.

Summary:

  • slice() extracts a portion of an array and returns it as a new array without modifying the original array.
  • The start index is inclusive, while the end index is exclusive.
  • It handles negative indices, allowing you to extract elements from the end of the array.
  • It's commonly used to copy an array or extract specific parts of an array.