JavaScriptArrays

Array.prototype.slice()

Returns a copy of part of an array without changing the original.

Returns
A new array with the extracted elements.
Changes the original
No
On this page

Example

#
JavaScript
const modules = ['Intro', 'HTML', 'CSS', 'Flexbox', 'Grid']

console.log(modules.slice(1, 3))
console.log(modules.slice(-2))
console.log(modules)
Console
['HTML', 'CSS']
['Flexbox', 'Grid']
['Intro', 'HTML', 'CSS', 'Flexbox', 'Grid']

Definition and usage

#

The slice(start, end) method cuts out part of the array from index start up to end, not including the element at end, and returns it as a new array. The original is left untouched.

Negative indexes count from the end: slice(-2) returns the last two elements. Calling it with no arguments makes a shallow copy of the whole array.

Don’t confuse it with splice(), which changes the array by removing or inserting elements. An easy way to remember: slice cuts a copy, splice operates on the original.

Syntax

#
Syntax
array.slice()
array.slice(start)
array.slice(start, end)

Parameters

#
  • start

    optional

    The start index (inclusive). A negative value counts from the end.
  • end

    optional

    The end index (exclusive). Defaults to the array’s length.

More examples

#
Pagination
JavaScript
const items = [1, 2, 3, 4, 5, 6, 7]
const perPage = 3
const page = 2

console.log(items.slice((page - 1) * perPage, page * perPage))
Console
[4, 5, 6]

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • slice() makes a shallow copy: the objects inside are shared between both arrays.
  • For paginating results, the pattern slice((page - 1) * size, page * size) is short and easy to read.

Related entries

#

Spotted a mistake or missing an example? Write to us.