freecoding.school100% FREE · NO SIGNUP
Closure CavesISSUE #20 of 61

array methods · slice · splice

LambdaVSThe Mutator
Lambda saysslice copies a section (non-mutating); splice inserts/removes in place (mutating).

slice(start, end) returns a shallow copy of a range and leaves the original alone — great for safe sub-arrays. splice(start, deleteCount, ...items) changes the array: removing, inserting, or replacing. The names are similar; the behaviors (copy vs mutate) are opposite — a common mix-up.

Power-ups you unlock

The Mutator attacks — common mistakes

Boss battleslice the middle of an array, then splice to remove and insert items.

Example code

<!doctype html><html><head><meta charset="utf-8"></head>
<body style="background:#06040d;color:#e6e0ff;font-family:monospace;padding:20px"><pre id="o"></pre>
<script>const a=[1,2,3,4,5]; const mid=a.slice(1,4); a.splice(0,1,'x');
document.getElementById('o').textContent='slice='+mid+'\nafter splice='+a;</script></body></html>
▶ Open the interactive comic issue
‹ Array Methods · Push · Pop · Shift · UnshiftArray Methods · Map · Filter · Reduce ›