Array Slice and Splice in JavaScript
Introduction
slice copies a portion of an array without mutating the original. splice changes the array in place. Confusing the two names is a classic beginner mistake—this chapter separates them with side-by-side examples.
Prerequisites
slice — Copy a Section
Syntax: array.slice(start, end) — end is exclusive
// slice returns new array
const nums = [10, 20, 30, 40, 50];
const middle = nums.slice(1, 4);
console.log(middle);
console.log(nums);Omit start for 0; omit end for through the end:
// From index 2 to end
const tail = nums.slice(2);
console.log(tail);
// Last two items
const lastTwo = nums.slice(-2);
console.log(lastTwo);splice — Mutate in Place
Syntax: array.splice(start, deleteCount, ...itemsToInsert)
// Remove 1 item at index 2
const letters = ["a", "b", "c", "d", "e"];
const removed = letters.splice(2, 1);
console.log(removed);
console.log(letters);Insert without removing:
// Insert at index 1, delete 0
letters.splice(1, 0, "x", "y");
console.log(letters);Quick Comparison
| Method | Mutates original? | Returns |
|---|---|---|
slice | No | New array (copy) |
splice | Yes | Array of removed items |
Shallow Copy Whole Array
// Copy all elements
const original = [{ id: 1 }, { id: 2 }];
const copy = original.slice();
copy.push({ id: 3 });
console.log(original.length);
console.log(copy.length);Nested objects are still shared—use structuredClone for deep copies when needed.
String slice Reminder
Strings also have .slice() but strings are immutable—methods return new strings.
Mini Example: Paginate Results
// Page 2 with page size 3
const allRows = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const pageSize = 3;
const page = 2;
const start = (page - 1) * pageSize;
const pageRows = allRows.slice(start, start + pageSize);
console.log(pageRows);FAQ
Does slice include the end index?
No—end is exclusive, like for loops and substring.
Can splice delete all items?
arr.splice(0, arr.length) clears in place—arr.length = 0 is simpler.
Why use slice on an array of objects?
To duplicate the outer array while cloning references—know whether you need deep clone.