Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

Array.prototype.slice

Returns part of an array.

Available since: ES3

Syntax

array.slice(start, end)

Parameters

ParameterTypeDescription
startnumberThe index to start from. A negative value counts from the end.
endnumberOptional. The index to stop before. Defaults to the end of the array.

Return value

ArrayA new array with the selected elements.

Examples

Elements at indexes 1, 2 and 3:

console.log([1, 2, 3, 4, 5].slice(1, 4).join(', '));

Output:

2, 3, 4

The last two elements:

console.log([1, 2, 3, 4, 5].slice(-2).join(', '));

Output:

4, 5

Notes

The source array is not modified. Do not confuse it with splice(), which removes elements from the array itself.

See also

Related recipes

In the tutorial

  • Array methods — How to add and remove array elements in JavaScript: push, pop, shift, unshift, slice, splice, concat and join.

Thanks for reading!

Donate to the site — we work hard for you.