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
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
#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
#- slice() vs splice()slice() copies a section of the array without changing the original, while splice() removes, inserts, or replaces elements in place, mutating the array.
- Array.prototype.splice()Removes, replaces, or inserts elements in place, changing the array.
- String.prototype.slice()Returns a portion of a string from a start index to an end index (not included). Supports negative indexes.
- Array.prototype.concat()Combines arrays and values into a new array.
- Spread (...)The spread syntax spreads an array, string, or object out into individual elements: for copying, merging, and passing arguments.
Spotted a mistake or missing an example? Write to us.