Javascript Fundamentals · Array Methods

Slice copies, splice mutates

slice vs splice

Slice copies, splice mutates

You have a list and you want a section of it — the first few entries, or everything between two indexes — without disturbing the original. But slice and splice sound alike and behave nothing alike. slice(start, end) returns a new array holding a shallow copy of the elements from start up to — but not including — end. It never changes the original, and the original's length stays the same.

splice(start, deleteCount, ...items) mutates the original: it removes deleteCount elements beginning at start, optionally inserts new items, and returns the removed elements in a new array. The original's length changes.

Picture a paper list. slice is photocopying a section: you get a new sheet and the original is untouched. splice is cutting a section out with scissors: the original sheet is now shorter, and you hold the cut-out piece.

const letters = ['a', 'b', 'c', 'd'];

letters.slice(1, 3); // ['b', 'c'] — a copy; letters is unchanged
letters.splice(1, 2); // ['b', 'c'] — letters is now ['a', 'd']

The return values look similar — both arrays — but only slice leaves its input alone. When you want the change without touching the caller's array, use toSpliced, the non-mutating twin of splice: it returns the edited copy and leaves the original as it was.

Export head and insertAfter from index.js. head returns the first n elements as a copy; insertAfter returns a new array with a value inserted after an index, leaving the input unchanged.

Challenge

You have a list and you want to take a copy of its first few entries, or slot a value in after a given index, while leaving the caller's list exactly as it was. Export head and insertAfter from index.js.

head(list, n) returns a new array of the first n elements, using slice, and leaves list unchanged. insertAfter(list, index, value) returns a new array with value inserted immediately after index, without mutating list. Before and after each call the original array must hold its original elements.

index.js
export function head(list, _n) {
  return list;
}

export function insertAfter(list, _index, _value) {
  return list;
}

export function render(mount) {
  const letters = ['a', 'b', 'c'];

  mount.innerHTML = `
    <p>head: ${head(letters, 2).join(', ')}</p>
    <p>insertAfter: ${insertAfter(letters, 1, 'x').join(', ')}</p>
    <p>Original: ${letters.join(', ')}</p>
  `;
}

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.