JavaScript Roadmap — Day 33: More Array Methods — slice() and splice()
More Array Methods — slice() and splice()
Two of the most powerful array methods — slice() extracts portions without modifying the original, while splice() can remove, add, and replace elements. Master these and you can manipulate arrays like a pro.
1. The Problem — Extracting and Modifying Parts of an Array
Sometimes you need to extract a portion of an array without changing the original. Other times, you need to remove, add, or replace elements anywhere in the array — not just at the beginning or end. This is where slice() and splice() come in.
Think of slice() as a copy machine — it takes a section of an array and gives you a new array without touching the original. Think of splice() as a surgery tool — it directly cuts, removes, or inserts elements into the original array.
The difference is crucial: slice() is non-destructive (doesn't change the original), while splice() is destructive (modifies the original array). Understanding this will save you from many bugs in your code.
š” The key insight: slice() is your go-to when you need to extract data for display or processing. splice() is for when you need to modify the actual array — like removing an item from a shopping cart.
2. slice() — Extract Without Modifying
The slice() method takes two parameters: start index (where to begin) and end index (where to stop — not included). It returns a new array containing the extracted elements. The original array remains untouched.
One of the most useful features of slice() is that it accepts negative indices. A negative index counts from the end of the array: -1 is the last element, -2 is the second last, and so on.
If you call slice() with no arguments, it creates a shallow copy of the entire array. This is a common pattern when you need to duplicate an array without referencing the original.
Question 1: What does slice() return?
3. splice() — The Array Surgery Tool
The splice() method is much more powerful than slice() — it can remove, add, and replace elements anywhere in an array. However, it modifies the original array directly.
The syntax is: array.splice(start, deleteCount, item1, item2, ...)
- start — The index where to begin (required)
- deleteCount — How many elements to remove (optional, defaults to rest of array)
- items — Elements to add (optional)
The name "splice" comes from the word "splicing" — joining or connecting things together. It's like performing surgery on your array: you can cut out parts (remove) and stitch in new parts (add).
Question 2: What does splice() return?
4. slice() vs splice() — Comparison
Choosing between slice() and splice() depends entirely on what you need to do. Here's a simple rule:
- Use slice() when: You need to extract data for display, processing, or copying — and you want to keep the original array intact.
- Use splice() when: You need to actually modify the array — removing, adding, or replacing elements permanently.
5. Common Mistakes to Avoid
6. Best Practices — Professional Advice
const newArray = oldArray.slice(); newArray.splice(1, 1);array.length - 2, just use -2. It's cleaner and less error-prone.slice() is perfect: let page = allItems.slice(page * itemsPerPage, (page + 1) * itemsPerPage);7. Try It Yourself — slice() vs splice() Playground
Experiment with slice() and splice() below. See the difference between non-destructive and destructive operations.
8. Practice Tasks
Task 1 — Easy: Extract First Three Items
Use slice() to extract the first three items from [10, 20, 30, 40, 50, 60]. Store the result in a new variable. Log both the original and the extracted array.
Task 2 — Medium: Remove Middle Element
Use splice() to remove the middle element from [1, 2, 3, 4, 5]. Log the removed element and the modified array.
Task 3 — Hard: Replace Items in an Array
Write a function replaceItems(arr, start, deleteCount, ...newItems) that uses splice() to replace items. Test by replacing positions 2-4 in [10, 20, 30, 40, 50, 60] with [99, 100].
Given an array [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], use slice() to extract the middle 4 elements (positions 3-6). Then use splice() to replace those 4 elements with [99, 88, 77, 66]. Log the array before and after.
š View Solution
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log("Before:", arr);
let middle = arr.slice(3, 7);
console.log("Extracted:", middle);
arr.splice(3, 4, 99, 88, 77, 66);
console.log("After:", arr);
- slice(start, end) — Extracts elements without modifying the original array
- splice(start, deleteCount, items...) — Removes, adds, or replaces elements — modifies the original
- Negative indices work with both methods (count from the end)
- slice() with no arguments creates a shallow copy of the entire array
- splice() returns an array of the removed elements (empty array if none removed)
- Always remember: slice() = safe copy, splice() = direct modification
❓ Q: What is the difference between slice() and splice()?
š” A: slice() extracts a portion without modifying the original array. splice() modifies the original array by removing, adding, or replacing elements.
❓ Q: How do you copy an array in JavaScript?
š” A: Using slice() with no arguments: let copy = original.slice();
❓ Q: What does splice() return?
š” A: An array containing the removed elements. If no elements are removed, it returns an empty array.