Slicing Arrays
JavaScript’s .slice() method makes it incredibly easy to extract a portion of an array without modifying the original array itself. It returns a brand new “shallow copy” containing the requested elements.
The Syntax
The .slice() method accepts two arguments:
- Start Index: Where the slice begins (inclusive).
- End Index: Where the slice ends (exclusive/non-inclusive). If omitted, the slice goes to the very end of the array.
const animals = ["ant", "bison", "camel", "duck", "elephant"];
// Start at index 2, go to the end
console.log(animals.slice(2));
// Output: ["camel", "duck", "elephant"]
// Start at index 2, end BEFORE index 4
console.log(animals.slice(2, 4));
// Output: ["camel", "duck"]
// Copy the entire array
console.log(animals.slice());
// Output: ["ant", "bison", "camel", "duck", "elephant"]
Negative Indexing
Unlike Python, JavaScript does not support accessing elements directly via negative index brackets (e.g., animals[-1]). However, the .slice() method does support negative indexes to represent offsets from the end of the array.
// Start 2 elements from the end
console.log(animals.slice(-2));
// Output: ["duck", "elephant"]
// Start at index 2, end 1 element from the end
console.log(animals.slice(2, -1));
// Output: ["camel", "duck"]