TypeScript slice() Method for Arrays
The slice() method in TypeScript extracts a portion of an array and returns a new array without modifying the original. It is a built-in function that works identically to JavaScript's Array.slice().
Syntax
array.slice(begin?: number, end?: number): T[]begin: Optional. Zero-based index to start extraction.If omitted, defaults to
0.Negative values count from the end of the array (e.g.,
-1is the last element).
end: Optional. Zero-based index to end extraction (exclusive).If omitted, extracts to the end of the array.
Negative values count from the end.
Key Behavior
Returns a shallow copy of the selected elements.
Does not mutate the original array.
For primitive values (
string,number,boolean), the values are copied.For objects, references are copied, so changes to nested objects affect both arrays.
Examples
const arr = ['a', 'b', 'c', 'd', 'e'];
// Extract from index 1 to 3 (exclusive)
const subArr = arr.slice(1, 3); // ['b', 'c']
// Extract from index 2 to end
const endSlice = arr.slice(2); // ['c', 'd', 'e']
// Use negative indices: last 2 elements
const lastTwo = arr.slice(-2); // ['d', 'e']
// Copy entire array
const copy = arr.slice(); // ['a', 'b', 'c', 'd', 'e']Use with Objects
const user1 = { name: 'Alice' };
const user2 = { name: 'Bob' };
const users = [user1, user2];
const sliced = users.slice(1);
sliced[0].name = 'Charlie'; // Also changes users[1].name to 'Charlie'When to Use slice() vs splice()
Use
slice()to extract a section (non-destructive).Use
splice()to remove or replace elements (destructive).
✅ Use
slice()when you need a new array without altering the original.
What's the difference between doing [].slice.call(array) and array.slice()? I've seen such []s used many times with the array inside the call. Why? Thanks!
My .slice() method mutate the original array (TypeScript) - Stack Overflow
eslint - Can I spread a TypeScript any array slice safely? - Stack Overflow
Splice an array into an array causing error to be thrown
Videos
EDIT: Thanks for the answers, magnificent people! So Array.from is a better way than [].slice.call, and they're used to provide the array prototype to array-like objects! If done directly, apparently errors are thrown.
Thanks!