Javascript - Array slice() Method

The slice() method returns the sub-array elements in an array as a new array object.

Description

The slice() method returns the sub-array elements in an array as a new array object.

The elements returned start at the given start index, and ends at, but does not include, the end index.

The original array will not be changed.

Syntax

array.slice(start,end)

Parameter Values

Parameter Require Description
start Optional. An integer to start the selection starting at 0. Use negative numbers to select from the end of an array. If omitted, it defaults to 0
end Optional. An integer to end the selection. If omitted, all elements from the start position and to the end of the array will be selected. Use negative numbers to select from the end of an array

Return

A new Array, containing the selected elements

Example

Extract the second and the third elements from the array.

Demo

var myArray = ["XML", "Json", "Lemon", "Database", "Mango"];
var citrus = myArray.slice(1, 3);
console.log( citrus );//from  ww w  .  ja  v a 2  s. c om

//Select elements using negative values: 
//extract the third and fourth elements, using negative numbers.

var myArray = ["XML", "Json", "Lemon", "Database", "Mango"];
var myBest = myArray.slice(-3, -1);
console.log( myBest );

Result