slice()

ES3+

Returns a shallow copy of a portion of an array into a new array object.

Syntax

array.slice(start, end)

Parameters

start number optional

Index at which to start extraction

end number optional

Index before which to end extraction

Return Value

Array

A new array containing the extracted elements

Examples

JavaScript
const fruits = ['apple', 'banana', 'cherry', 'date'];
console.log(fruits.slice(1, 3));
console.log(fruits.slice(-2));
Output:
// ['banana', 'cherry'] ['cherry', 'date']

📌 When to Use

Use slice() when you need to extract a portion of an array without modifying the original. Perfect for pagination, getting the last N items, shallow copying arrays, or implementing immutable update patterns.

⚠️ Common Mistakes

Confusing slice() with splice() - slice() is non-mutating and returns a new array

Forgetting that the end index is exclusive - slice(0, 2) returns indices 0 and 1 only

Expecting slice() to create a deep copy - it only creates a shallow copy

✅ Best Practices

Use slice() to copy an array: const copy = arr.slice() or use spread [...arr]

Use negative indices to get elements from the end: arr.slice(-3) for last 3 items

Combine with spread for immutable updates: [...arr.slice(0, i), newItem, ...arr.slice(i+1)]

⚡ Performance Notes

slice() creates a new array, which has O(n) time and space complexity where n is the size of the slice. For very large arrays, avoid unnecessary slicing. The spread operator [...arr] is comparable in performance to slice().

🌍 Real World Example

Implementing Pagination

Extract a page of items from a large list for display

const allProducts = [...]; // 1000 products

function getPage(items, pageNum, pageSize = 10) {
  const start = (pageNum - 1) * pageSize;
  const end = start + pageSize;
  return items.slice(start, end);
}

const page1 = getPage(allProducts, 1);  // items 0-9
const page2 = getPage(allProducts, 2);  // items 10-19

// Get last 5 items
const recentItems = allProducts.slice(-5);

Related Methods