4Geeks chosen to deliver AI education in the Bahamas alongside Harvard, Oxford, and Columbia.See more

How to use the slice method of Arrays in Javascript?

By 4Geeks

Copy part of an array with slice(start, end), count from the end, tell slice() and splice() apart and paginate lists.

6 min readLast updated
JavaScript array slice() icon

What does slice() do in JavaScript?

Short answer: array.slice(start, end) returns a new array with the items from start up to end, without including end. The original array doesn't change. Negative numbers count from the end, so slice(-2) gives the last two items.

javascript
const fruits = ["apple", "banana", "cherry", "kiwi"];
 
fruits.slice(1, 3);   // ["banana", "cherry"]
fruits.slice(-2);     // ["cherry", "kiwi"]
console.log(fruits);  // ["apple", "banana", "cherry", "kiwi"]  unchanged

Don't confuse it with splice(), which removes items from the original array.

slice() copies a range without the end position, counts from the end with negative numbers and never changes the original array.

slice() at a glance

What you wantCodeResult
From position 1 to 3 (3 not included)fruits.slice(1, 3)["banana", "cherry"]
From position 2 to the endfruits.slice(2)["cherry", "kiwi"]
The last 2 itemsfruits.slice(-2)["cherry", "kiwi"]
Everything except the lastfruits.slice(0, -1)["apple", "banana", "cherry"]
The first 3 itemsfruits.slice(0, 3)["apple", "banana", "cherry"]
A copy of the whole arrayfruits.slice()A new array with the same items
Page 2 of 3 items per pageitems.slice(3, 6)Items 4 to 6
Part of a string"hello world".slice(0, 5)"hello"

Syntax of slice()

javascript
array.slice()
array.slice(start)
array.slice(start, end)
  • start (optional): the first position to copy. By default 0.
  • end (optional): where to stop. This position is not included. By default, the end of the array.

Both accept negative numbers: -1 is the last position, -2 the one before it. If start is greater than end, or beyond the length, you get an empty array: fruits.slice(3, 1) is [].

Career · AI Engineering for Developers

You already master JavaScript arrays, now build AI apps with them

Use the coding skills you already have to build AI agents, RAG systems and LLM-powered apps, with mentors and real projects.

slice() vs splice()

The names are similar, but they do very different things:

slice(start, end)splice(start, count)
Changes the original arrayNoYes
ReturnsA copy of the rangeThe removed items
Second argumentEnd position (not included)How many items to remove
Can insert itemsNoYes: splice(1, 0, "new")
javascript
const nums = [1, 2, 3, 4, 5];
 
console.log(nums.slice(1, 3));    // [2, 3]
console.log(nums);                // [1, 2, 3, 4, 5]
 
console.log(nums.splice(1, 2));   // [2, 3]
console.log(nums);                // [1, 4, 5]

If you want splice() without changing the original, use toSpliced(), available in current browsers and Node.js 20 or newer.

Get the first or last items

javascript
const scores = [90, 85, 77, 64, 58];
 
scores.slice(0, 3);    // [90, 85, 77]  top 3
scores.slice(-2);      // [64, 58]      last 2
scores.slice(1);       // [85, 77, 64, 58]  all except the first
scores.slice(0, -1);   // [90, 85, 77, 64]  all except the last

For a single item, scores.at(-1) returns 58 directly, without an array.

Copy an array with slice()

slice() with no arguments copies the whole array. Changing the copy doesn't change the original:

javascript
const original = [1, 2, 3];
const copy = original.slice();
copy.push(4);
 
console.log(original);   // [1, 2, 3]
console.log(copy);       // [1, 2, 3, 4]

It's a shallow copy: objects inside are shared, so changing copy[0].name also changes the original. For a deep copy, use structuredClone(original).

Paginate a list

javascript
const items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const pageSize = 3;
const page = 2;
 
const pageItems = items.slice((page - 1) * pageSize, page * pageSize);
console.log(pageItems);   // [4, 5, 6]

slice() doesn't fail if the end goes past the length, so the last page simply has fewer items.

slice() with strings and array-like objects

Strings have their own slice() with the same rules:

javascript
"hello world".slice(0, 5);   // "hello"
"hello".slice(-3);           // "llo"

To turn arguments or a NodeList into an array, Array.from() is the modern choice. Older code uses Array.prototype.slice.call(list), which does the same.

Use AI to work with slice()

An assistant like ChatGPT, Claude or GitHub Copilot can write the right indexes and explain an unexpected result. These three prompts are ready to copy.

1. Get part of an array

In JavaScript I have this array: [paste a short example].
I need [the first 3 / the last 2 / from the 2nd to the 5th] items without changing it.
Show me the code with slice() and explain the numbers.

2. Explain a result

This JavaScript code: [paste your code]
returns [what you see] and I expected [what you expected].
Explain why and how to fix it.

3. Paginate data

I have an array of [number] items in JavaScript and I want to show [number] per page.
Write a function that returns the items of a given page and the total number of pages.

Test the answer with the first page, the last page and a page that doesn't exist.

Learn with a mentor

From array methods to shipping AI features

In the 4Geeks AI Engineering for Developers program you add AI agents, RAG and production LLM apps to your portfolio.

Common problems with slice()

What you seeWhy it happensFix
The last item you wanted is missingend is not includedUse one position more: slice(1, 4)
slice() returns []start is greater than end, or past the lengthCheck the order and the length
The original array changedYou used splice(), not slice()Use slice(), or toSpliced()
Changing the copy changes objects in the originalslice() makes a shallow copystructuredClone(original) for a deep copy
TypeError: Cannot read properties of null (reading 'slice')The variable is null or undefinedCheck the value first, or use arr?.slice(0, 3)
TypeError: ... .slice is not a functionThe value is an object, not an array or stringConvert it with Array.from() or Object.values()
Decimal positions behave oddlyPositions are truncated: slice(1.7) is slice(1)Use whole numbers, for example with Math.floor()
Free download

JavaScript slice() in a 2-page cheat sheet

slice() with start and end, negative positions, slice() vs splice(), copies, pagination, strings, common errors and prompts for ChatGPT, Claude or Copilot. Free, in PDF.

JavaScript array slice() cheat sheet

2 pages · PDF · 4Geeks

  • slice() recipes ready to copy
  • slice() vs splice() side by side
  • Common errors and prompts to solve them with AI

Get it free

Your PDF right away

Frequently asked questions about JavaScript array slice()

Want to go from array methods to building AI apps, with real projects and mentors?

See the AI Engineering for Developers program