Easy Tutorial
❮ Jsref Setfullyear Met Document Renamenode ❯

JavaScript Array slice() Method

JavaScript Array Object

Example

Reading elements from an array:

var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1,3);

citrus output result:


Definition and Usage

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

The slice() method extracts a section of a string and returns it as a new string, without modifying the original string.

Note: The slice() method does not alter the original array.


Browser Support

All major browsers support the slice() method.


Syntax

Parameter Values

Parameter Description
start Optional. Specifies where to start the selection. If negative, it indicates an offset from the end of the array. For example, slice(-2) extracts the last two elements of the array.
end Optional. Specifies where to end the selection. This parameter is the index at which to stop slicing (not inclusive). If not specified, the slice includes all elements from start to the end of the array. If negative, it indicates an offset from the end of the array. For example, slice(-2, -1) extracts the second to last element only.

Return Value

Type Description
Array Returns a new array containing the elements from start (inclusive) to end (exclusive) of the original array.

Technical Details

| JavaScript Version: | 1.2 | | --- | --- |


More Examples

Example

Using negative values to read elements from an array:

var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var myBest = fruits.slice(-3, -1); // Extracts the third to last and the second to last elements
var myBest = fruits.slice(-3);  // Extracts the last three elements

myBest output result:

Example

Slicing a string:

var str = "www.tutorialpro.org!";
document.write(str.slice(4) + "<br>"); // Extracts from the 5th character to the end
document.write(str.slice(4, 10)); // Extracts from the 5th character to the 10th character

JavaScript Array Object

❮ Jsref Setfullyear Met Document Renamenode ❯