slice() for Extracting Array Portions
What you'll learn: How to extract a section of an array into a new array without changing the original.
The Core Idea
The slice() method creates a shallow copy of a portion of an array. Unlike splice(), which mutates the original array, slice() leaves your original array completely untouched and returns a brand new array containing the extracted elements.
Think of it like photocopying specific pages from a book — the original book stays intact, and you get a separate copy of just the pages you wanted.
Basic Syntax
const fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
const some = fruits.slice(1, 4);
console.log(some); // ['banana', 'cherry', 'date']
console.log(fruits); // ['apple', 'banana', 'cherry', 'date', 'elderberry']
The first parameter is the start index (inclusive), and the second is the end index (exclusive).
Common Patterns
const numbers = [10, 20, 30, 40, 50];
// From index to end
const fromTwo = numbers.slice(2);
console.log(fromTwo); // [30, 40, 50]
// Negative indices (count from end)
const lastTwo = numbers.slice(-2);
console.log(lastTwo); // [40, 50]
// Copy entire array
const copy = numbers.slice();
console.log(copy); // [10, 20, 30, 40, 50]
Negative indices work backward from the end: -1 is the last element, -2 is second-to-last, and so on.
Why This Matters
When you need to work with part of an array but want to preserve the original data, slice() is your tool. It's perfect for creating copies, extracting ranges, or preparing data for further processing without side effects.
Key Takeaway: slice() extracts a portion of an array into a new array without mutating the original — use it when you need a non-destructive copy of array elements.