splice Mutates While slice Only Reads
slice copies a range and leaves the array untouched, while splice deletes or inserts in place and returns removed elements; mixing them corrupts shared data.
Code
// slice: pure read, returns a shallow copy of [start, end), negative indices counting from the end
const roster = ['ada', 'bob', 'cyd', 'dee'];
console.log('slice(1, 3) :', roster.slice(1, 3).join(','));
console.log('after slice :', roster.join(','));
// splice: writes in place, returning an array of the removed elements
const removed = roster.splice(1, 2, 'new-hire'); // removes 2 elements at index 1, then inserts
console.log('removed :', removed.join(','));
console.log('after splice :', roster.join(','));
// splice(0, 0, x) inserts at an exact position without removing anything
roster.splice(0, 0, 'lead');
console.log('insert at 0 :', roster.join(','));
// negative start: splice(-1, 1) plucks off the last element
console.log('pop via splice:', roster.splice(-1, 1).join(','), '->', roster.join(','));How it works
Top-level bindings roster, removed hold the demo state — nothing sits inside a function scope.
Using it
The run emits 6 labeled sections — slice(1, 3) :, after slice :, removed :, after splice :, insert at 0 :, pop via splice: — one per step.
Key statements
const removed = roster.splice(1, 2, 'new-hire'); // removes 2 elements at index 1, then inserts
console.log('removed :', removed.join(','));
const roster = ['ada', 'bob', 'cyd', 'dee'];
roster.splice(0, 0, 'lead');
Interactive Tools for This Topic
FAQ
- Any setup needed beyond the language runtime?
- None — the language runtime is the only requirement. Its state lives in module-level bindings: `roster`, `removed`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.