Course contentsShow
← JavaScript
Lesson 911 of 2,72320. Array Iteration and TransformationFree lesson

Immutable .slice() for Copying and Extracting

Use slice to create shallow copies or extract subarrays without altering the original.

Immutable .slice() for Copying and Extracting

You'll learn how to use .slice() to create shallow copies and extract portions of arrays without modifying the original.

What Makes .slice() Immutable?

Unlike mutating methods that change an array in place, .slice() always returns a new array. The original remains untouched. This makes it perfect for working with data in an immutable way—a cornerstone of predictable, bug-free code.

Creating Shallow Copies

Call .slice() with no arguments to duplicate an entire array:

const original = [1, 2, 3, 4, 5];
const copy = original.slice();

copy.push(6);

console.log(original); // [1, 2, 3, 4, 5] — unchanged!
console.log(copy);     // [1, 2, 3, 4, 5, 6]

Extracting Subarrays

Pass start and end indices to extract a portion. Remember: the end index is exclusive (not included):

const numbers = [10, 20, 30, 40, 50];
const middle = numbers.slice(1, 4);

console.log(middle);  // [20, 30, 40]
console.log(numbers); // [10, 20, 30, 40, 50] — still intact

Practical Examples

Omit the end parameter to slice from a start position to the array's end:

const items = ['a', 'b', 'c', 'd'];
const lastTwo = items.slice(2);

console.log(lastTwo); // ['c', 'd']

Use negative indices to count from the end:

const values = [1, 2, 3, 4, 5];
const lastThree = values.slice(-3);

console.log(lastThree); // [3, 4, 5]

Key Takeaway: .slice() is your go-to method for copying arrays or extracting portions immutably—it never touches the original, making your code safer and more predictable.