**slice(start, end)** extracts elements from index `start` up to (but not including) `end`. Both are optional: `slice()` copies the whole array. Negative indices count from the end. It performs a **shallow copy** — nested objects are still references.
1Understanding Array.slice()
slice(start, end) extracts elements from index start up to (but not including) end. Both are optional: slice() copies the whole array. Negative indices count from the end. It performs a shallow copy — nested objects are still references.
slice() is the safe way to copy an array: [...arr] and arr.slice() are equivalent. Use slice for extracting sub-arrays without mutation.
const arr = ['a', 'b', 'c', 'd', 'e'];
console.log(arr.slice(1, 3)); // ['b', 'c']
console.log(arr.slice(2)); // ['c', 'd', 'e']
console.log(arr.slice(-2)); // ['d', 'e'] (last 2)
console.log(arr.slice()); // full copy
console.log(arr); // ['a','b','c','d','e'] (unchanged!)2Practical Example
Here is a real-world application of Array.slice() showing how it is used in production JavaScript code.
// Implement pagination
function paginate(data, page, pageSize) {
const start = (page - 1) * pageSize;
return data.slice(start, start + pageSize);
}
const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log(paginate(data, 2, 3)); // [4, 5, 6]3Best Practices
Follow these guidelines when working with Array.slice():
1. Use slice() to safely copy arrays without mutation
2. Use negative indices for 'last N elements': arr.slice(-3)
3. Remember slice(start, end) — end is exclusive
Tip: slice() is the safe way to copy an array: [...arr] and arr.slice() are equivalent. Use slice for extracting sub-arrays without mutation.
const arr = ['a', 'b', 'c', 'd', 'e'];
console.log(arr.slice(1, 3)); // ['b', 'c']
console.log(arr.slice(2)); // ['c', 'd', 'e']
console.log(arr.slice(-2)); // ['d', 'e'] (last 2)
console.log(arr.slice()); // full copy
console.log(arr); // ['a','b','c','d','e'] (unchanged!)