Skip to content
jshacks.dev
Fundamentals

JavaScript Array slice Explained Step by Step With Code

Array slice() copies part of an array without changing it. Learn start and end rules, negative indexes, shallow copies, holes and the splice mix-up.

8 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, TypeScript and npm logos.

slice() and splice() differ by one letter and by everything that matters: one copies, the other destroys. People who mix them up either lose data they meant to keep or discover that a "removal" never removed anything. slice() also has a rule that surprises even careful readers, because the end index is exclusive, so slice(1, 3) returns two elements, not three. This post covers the arguments, negative indexes, the shallow copy and what it means for nested data, how holes and array-likes behave, and where at(), toSpliced() or a different structure is the better call. Everything runs on Node.js 24. The mutating sibling is in [the post on splice()](/library/javascript-array-splice), and a sibling that returns a modified copy is [toSpliced()](/library/javascript-array-tospliced).

What slice() takes and returns

The signature is array.slice(start, end). It returns a new array holding the elements from index start up to, but not including, index end. The original is never changed.

ArgumentMeaningDefault
startIndex to begin copying at0
endIndex to stop beforearray.length
CallResult
slice()A shallow copy of the whole array
slice(2)Everything from index 2 to the end
slice(1, 3)Indexes 1 and 2
slice(-2)The last two elements
JavaScript
const days = ["mon", "tue", "wed", "thu", "fri"];

console.log(days.slice(1, 3));
console.log(days.slice(2));
console.log(days.slice());
console.log(days);
Text
[ 'tue', 'wed' ]
[ 'wed', 'thu', 'fri' ]
[ 'mon', 'tue', 'wed', 'thu', 'fri' ]
[ 'mon', 'tue', 'wed', 'thu', 'fri' ]

The last line proves nothing was removed. The exclusive end is deliberate: slice(a, b) returns exactly b - a elements when the range fits, and slice(0, n) is the first n, which makes arithmetic on ranges easy.

Negative indexes count from the end

A negative start or end is added to the array's length. If the result is still below zero, it becomes 0.

JavaScript
const nums = [10, 20, 30, 40, 50];

console.log(nums.slice(-2));
console.log(nums.slice(1, -1));
console.log(nums.slice(-100, 2));
console.log(nums.slice(3, 1));
Text
[ 40, 50 ]
[ 20, 30, 40 ]
[ 10, 20 ]
[]

slice(-2) is the last two items. slice(1, -1) drops the first and the last, which is the idiom for trimming both ends. An oversized negative start clamps to 0, and a start that is at or after the end returns an empty array, not an error. Out-of-range values never throw.

Odd arguments are coerced

The arguments pass through integer conversion, so the method is forgiving, sometimes too forgiving.

JavaScript
const list = ["a", "b", "c", "d"];

console.log(list.slice(1.9));
console.log(list.slice("2"));
console.log(list.slice(NaN));
console.log(list.slice(undefined, 2));
console.log(list.slice(1, undefined));
Text
[ 'b', 'c', 'd' ]
[ 'c', 'd' ]
[ 'a', 'b', 'c', 'd' ]
[ 'a', 'b' ]
[ 'b', 'c', 'd' ]

A fractional 1.9 is truncated toward zero to 1. The string "2" converts to the number 2. NaN becomes 0. An explicit undefined for end means "to the end", the same as omitting it. This leniency is why a bad index in a computed range, such as NaN from a failed parse, returns a plausible array instead of an error. Validate numbers before they reach slice().

It is a shallow copy

slice() copies the container, not what is inside. Primitives are copied by value, and objects are copied by reference, so both arrays point at the same objects.

JavaScript
const original = [{ n: 1 }, { n: 2 }];
const copy = original.slice();

copy[0].n = 99;
copy.push({ n: 3 });

console.log(original);
console.log(copy);
console.log(original[0] === copy[0]);
Text
[ { n: 99 }, { n: 2 } ]
[ { n: 99 }, { n: 2 }, { n: 3 } ]
true

Pushing onto copy did not change original, because the arrays are separate. Editing a field on the first object changed both, because the objects are shared. For nested data you need a deeper copy, and structuredClone() is the built-in for that. Reaching for slice() to "protect" an array of objects protects only the order and length.

Holes are preserved

The result keeps the shape of a sparse source: missing indexes stay missing.

JavaScript
const sparse = [1, , 3, , 5];
const part = sparse.slice(1, 4);

console.log(part);
console.log(part.length);
console.log(0 in part);
Text
[ <1 empty item>, 3, <1 empty item> ]
3
false

The slice covers indexes 1, 2 and 3, and indexes 1 and 3 were holes. The copy therefore starts with a hole at index 0, and 0 in part is false. Copying with spread, by contrast, turns holes into undefined, so slice() is the faithful copier if you care about sparseness.

Array-likes and the classic idiom

For years, Array.prototype.slice.call(arguments) was how you converted an arguments object into a real array. The method is generic: it needs length and indexed properties.

JavaScript
const like = { 0: "x", 1: "y", 2: "z", length: 3 };

const real = Array.prototype.slice.call(like, 1);

console.log(real);
console.log(Array.isArray(real));
Text
[ 'y', 'z' ]
true

The result is a proper array. Today Array.from(like) or rest parameters say the same thing more clearly, and [the post on Array.from()](/library/javascript-array-from) shows the modern form. The borrowed slice() call is still worth recognizing when you read older code.

Common recipes

Three small patterns cover most real uses. Paginating a list uses start and end computed from a page number.

JavaScript
const rows = ["r1", "r2", "r3", "r4", "r5", "r6", "r7"];
const page = 2;
const size = 3;

const view = rows.slice((page - 1) * size, page * size);

console.log(view);
Text
[ 'r4', 'r5', 'r6' ]

Taking the last few items uses a negative start, and splitting into head and tail uses two slices.

JavaScript
const log = ["a", "b", "c", "d", "e"];

const [head, tail] = [log.slice(0, 2), log.slice(2)];

console.log(head);
console.log(tail);
console.log(log.slice(-2));
Text
[ 'a', 'b' ]
[ 'c', 'd', 'e' ]
[ 'd', 'e' ]

A mistake we hit: slice and splice swapped

A pagination helper was meant to read a page and leave the list intact. A teammate typed splice where slice was meant.

JavaScript
const feed = ["p1", "p2", "p3", "p4", "p5"];

const viaSplice = feed.splice(1, 2);

console.log(viaSplice);
console.log(feed);
Text
[ 'p2', 'p3' ]
[ 'p1', 'p4', 'p5' ]

The returned values looked right in a quick test, so the bug passed review. The side effect was the damage: feed lost two items on every call, and the second page read different data than the first. With slice the same arguments return the same two items and leave feed whole.

JavaScript
const feed2 = ["p1", "p2", "p3", "p4", "p5"];

console.log(feed2.slice(1, 3));
console.log(feed2);
Text
[ 'p2', 'p3' ]
[ 'p1', 'p2', 'p3', 'p4', 'p5' ]

Note the argument shift too. splice(1, 2) means start and a count of two, while slice(1, 3) means start and an exclusive end. The different meaning of the second argument is the second half of this mix-up.

slice() compared with its neighbors

MethodMutatesReturnsSecond argument
slice()NoNew array of the rangeEnd index, exclusive
splice()YesArray of removed itemsDelete count
toSpliced()NoNew array with the edit appliedSkip count
at()NoOne elementNot applicable
Array.from()NoNew array from any iterableOptional map function

Slice, copy and spread

There are several ways to copy an array, and they differ in small ways. slice() with no arguments copies the container and preserves holes. The spread form [...list] also copies the container but reads through the iterator, so holes become undefined. Array.from(list) behaves like spread for arrays and also accepts array-likes and iterables, and it takes an optional mapping function. structuredClone(list) copies the container and every nested object, which none of the others do. When you only need a quick shallow copy of a dense array, all of the first three produce the same result, and the choice is about readability.

The second half of the decision is intent. Writing slice() signals that a copy or a range is wanted. Writing spread signals that you are building a new array from parts. Both are fine, and a team should pick one for plain copies so that readers do not wonder whether the difference was intentional. We use slice() when we mean a range and spread for plain copies, which keeps the two meanings apart.

One more detail is the cost of copying itself. A copy takes work proportional to the number of elements, so copying a large array inside a loop turns a linear task into a quadratic one. When a function only reads from part of an array, pass the array and two indexes instead of slicing on every call. That moves the range into arguments and avoids allocating at all, which matters mainly in recursive code that peels one element off the front on every level.

Slicing also interacts with sorted data. After sorting, slice(0, n) gives the smallest n and slice(-n) gives the largest n. Sorting a large list only to take a few items is wasteful, but for small lists the two-step form is the clearest way to say it, and the result is a fresh array that can be edited without affecting the source.

Where slice stops being the right tool

slice() stops being right when you need to read one element, where at(-1) or list[0] is shorter and does not allocate. It stops being right when you need a deep copy, because it shares nested objects, and structuredClone() is the dependable tool. It also stops being right for edits: removing or inserting in the middle while keeping the original is a job for [toSpliced()](/library/javascript-array-tospliced), which Node.js 24 provides, rather than two slices and a concat.

One more limit: a repeated slice(1) inside a recursive function, a common functional-style way to walk a list, makes a new array at every level. That is fine for short inputs and wasteful for large ones. An index parameter that moves forward avoids the copies.

The method is defined as Array.prototype.slice in the specification, and MDN documents it on the Array.prototype.slice page. It has been available since the first standardized edition.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.