The slice() method is one of the most versatile and frequently used tools in the JavaScript Array prototype. It returns a shallow copy of a portion of an array into a new array object. The most critical aspect of slice() is that it is non-mutating—the original array remains completely untouched.
1. Syntax
array.slice(start, end)
Parameters
start (Optional): The zero-based index at which to begin extraction.
- If undefined, it defaults to 0.
- If negative, it indicates an offset from the end of the sequence (e.g., -2 extracts the last two elements).
end (Optional): The zero-based index before which to end extraction. slice extracts up to but not including the end.
- If omitted, slice extracts through the end of the sequence.
- If negative, it indicates an offset from the end of the sequence.
2. Common Usage Patterns
A. Extracting a Sub-section
This is the standard use case where you want a specific “slice” of data.
const animals = ['Ant', 'Bison', 'Camel', 'Duck', 'Elephant'];
console.log(animals.slice(2)); // ["Camel", "Duck", "Elephant"]
console.log(animals.slice(2, 4)); // ["Camel", "Duck"] (Index 4 is excluded)
console.log(animals.slice(1, 5)); // ["Bison", "Camel", "Duck", "Elephant"]
B. Using Negative Indices
Negative indices allow you to target elements relative to the end of the array without calculating the length manually.
const colors = ['Red', 'Green', 'Blue', 'Yellow', 'Purple'];
// Get the last two elements
console.log(colors.slice(-2)); // ["Yellow", "Purple"]
// Get everything except the first and last element
console.log(colors.slice(1, -1)); // ["Green", "Blue", "Yellow"]
C. Creating a Full Copy (Cloning)
By calling slice() without any arguments, you create a perfect shallow clone of the entire array. This is a classic pattern used before the Spread operator ([...]) became popular.
const original = [1, 2, 3];
const clone = original.slice();
clone.push(4);
console.log(original); // [1, 2, 3] (Original is safe)
console.log(clone); // [1, 2, 3, 4]
3. Shallow Copy Behavior
It is vital to understand that slice() does not create a “Deep Copy.” It copies object references into the new array. Both the original and the new array refer to the same object in memory.
const basket = [{ item: 'Apple' }, { item: 'Orange' }];
const slicedBasket = basket.slice(0, 1);
// Modifying an object inside the slice
slicedBasket[0].item = 'Banana';
// The change is reflected in the original array!
console.log(basket[0].item); // "Banana"
4. Converting Array-like Objects
In older versions of JavaScript, slice() was the standard trick to convert “Array-like” objects (such as arguments or NodeList) into real arrays. While Array.from() is now preferred, you will still see this in legacy codebases:
function list() {
// Converts 'arguments' object into a real Array
return Array.prototype.slice.call(arguments);
}
const args = list(1, 2, 3); // [1, 2, 3]
