How to Use Slice in JavaScript Array: Simple Guide
Use the
slice(start, end) method on a JavaScript array to get a new array containing elements from the start index up to but not including the end index. If end is omitted, it slices until the end of the array.Syntax
The slice method is called on an array and takes two optional parameters:
- start: The index where slicing begins (inclusive). Defaults to 0 if omitted.
- end: The index where slicing ends (exclusive). Defaults to the array's length if omitted.
The method returns a new array with the selected elements and does not change the original array.
javascript
array.slice(start, end)
Example
This example shows how to use slice to get parts of an array without changing the original array.
javascript
const fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry']; const part1 = fruits.slice(1, 3); // from index 1 to 2 const part2 = fruits.slice(2); // from index 2 to end console.log(part1); console.log(part2); console.log(fruits);
Output
[ 'banana', 'cherry' ]
[ 'cherry', 'date', 'elderberry' ]
[ 'apple', 'banana', 'cherry', 'date', 'elderberry' ]
Common Pitfalls
Common mistakes when using slice include:
- Forgetting that the
endindex is exclusive, so the element atendis not included. - Using negative indexes incorrectly. Negative values count from the end of the array.
- Expecting
sliceto modify the original array—it does not.
javascript
const numbers = [10, 20, 30, 40, 50]; // Wrong: expecting element at index 3 included const wrongSlice = numbers.slice(1, 3); console.log(wrongSlice); // Outputs [20, 30], not including 40 // Correct: to include element at index 3, use end as 4 const correctSlice = numbers.slice(1, 4); console.log(correctSlice); // Outputs [20, 30, 40] // Using negative indexes const negativeSlice = numbers.slice(-3, -1); console.log(negativeSlice); // Outputs [30, 40]
Output
[ 20, 30 ]
[ 20, 30, 40 ]
[ 30, 40 ]
Quick Reference
Remember these key points about slice:
- Returns a new array without changing the original.
startis inclusive,endis exclusive.- Negative indexes count from the end.
- If
endis omitted, slices to the end.
Key Takeaways
Use
slice(start, end) to get a part of an array without changing the original.start index is included, but end index is excluded in the result.Negative indexes count from the end of the array.
If you omit
end, slicing continues to the array's end.slice always returns a new array.