slice vs splice in JavaScript
Two similar names, opposite contracts: slice(start, end) copies a range into a new array (non-mutating, end-exclusive, negatives count from the end), while splice(start, deleteCount, ...items) mutates in place — deleting, inserting, and replacing — returning the removed elements.
Mnemonic: slice with a C copies a section; splice with a P performs surgery in place. Confusing them either mutates shared arrays unexpectedly or wonders why nothing changed — the most common array-method mix-up after sort's string default.
slice copies out
arr.slice(1, 3) returns elements 1–2 in a new array — original untouched, negatives index from the end.
splice operates in place
arr.splice(1, 2, "x") deletes two from index 1, inserts "x", and returns the removed pair.
Returns differ
slice returns the extracted section; splice returns the removed elements (insertions stay in the array).
C copies, P performs
sliCe → Copy; sPlice → Place surgery — the mnemonic that ends the confusion permanently.
let a = [1, 2, 3, 4];console.log(a.slice(1, 3), a.length);console.log(a.splice(1, 2), a.length);Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in JavaScript yourself — building beats watching.