Hiprup

What is the difference between slice() and splice()?

They sound alike but behave very differently.

  • slice — returns a shallow copy of a portion of an array and leaves the original untouched. Non-mutating.

  • splice — removes, replaces, or inserts items in place and returns the removed items. Mutating.

Easy to remember: slice is safe (it copies); splice surgically changes the original.

const arr = [1, 2, 3, 4, 5];

// slice - does NOT modify original
const sliced = arr.slice(1, 3);  // [2, 3] — new array
console.log(arr);                 // [1, 2, 3, 4, 5] — unchanged
const copy = arr.slice();         // [1, 2, 3, 4, 5] — shallow copy
const last2 = arr.slice(-2);      // [4, 5] — from end

// splice - MODIFIES original
const removed = arr.splice(1, 2); // removes 2 elements at index 1
console.log(removed);              // [2, 3] — removed elements
console.log(arr);                  // [1, 4, 5] — modified!

// splice to insert
arr.splice(1, 0, 'a', 'b');       // insert at index 1, delete 0
console.log(arr);                  // [1, 'a', 'b', 4, 5]

// splice to replace
arr.splice(1, 2, 'x');            // remove 2 at index 1, insert 'x'
console.log(arr);                  // [1, 'x', 4, 5]

slice(1,3) extracts indices 1 and 2 (end exclusive), original unchanged. splice(1,2) removes 2 elements starting at index 1, modifying the original. splice(1, 0, 'a', 'b') inserts without deleting. splice(1, 2, 'x') replaces 2 elements with one.

slice = non-mutating (returns new array), splice = mutating (modifies original). The mnemonic: splice has a 'p' for 'permanent change.' slice() with no args for shallow copy. splice can insert (deleteCount=0), remove, and replace.

What is the difference between slice() and splice()? | Hiprup