JavaScript Array slice() method

JavaScript Array slice() method extracts the part of the given array and returns it.

In this tutorial, you will learn about the JavaScript Array slice() method with the help of examples.

The slice() method returns selected elements in an array, as a new array.

JavaScript Array slice() method doesn’t change the original array.


array.slice(start, end)
  • start – It is optional. It represents the index from where the method starts to extract the elements. Default is 0.
  • end – It is optional. It represents the index at where the method stops extracting elements. Default is last element.

The slice() method selects from a given start, up to a (not inclusive) given end.

Negative numbers select from the end of the array.

Return Value

A new array containing the selected elements. (end not included)

slice() is an ECMAScript1 (ES1) feature.


const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

// expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]

console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]

// expected output: Array ["duck", "elephant"]

console.log(animals.slice(2, -1));
// expected output: Array ["camel", "duck"]

// expected output: Array ["ant", "bison", "camel", "duck", "elephant"]
let fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
let citrus = fruits.slice(1, 3)

// fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
// citrus contains ['Orange','Lemon']
let numbers = [2, 3, 5, 7, 11, 13, 17];

// create another array by slicing numbers from index 3 to 5
let newArray = numbers.slice(3, 6);

// Output: [ 7, 11, 13 ]
let languages = ["JavaScript", "Python", "C", "C++", "Java"];

// slicing the array (from start to end)
let new_arr = languages.slice();
console.log(new_arr); // [ 'JavaScript', 'Python', 'C', 'C++', 'Java' ]

// slicing from the third element
let new_arr1 = languages.slice(2);
console.log(new_arr1); // [ 'C', 'C++', 'Java' ]

// slicing from the second element to fourth element
let new_arr2 = languages.slice(1, 4);
console.log(new_arr2); // [ 'Python', 'C', 'C++' ]