Skip to content
Tutorials Center
My learning

Topics

Lesson 50 of 156 ยท Arrays

Adding, Removing and Slicing

Add and remove array items with push, pop, shift, unshift and splice, copy parts with slice, and use concat, join, toSpliced and with without mutating.

Arrays rarely stay the same size. Items get added to a cart, removed from a queue, inserted into the middle of a playlist. JavaScript has a method for each of these jobs, and this lesson walks through them: the four end-of-array methods (push, pop, shift, unshift), the Swiss-army knife splice, its harmless look-alike slice, plus concat and join.

Along the way, keep one question in mind: does this method change the original array, or return a new one? Methods that change the array in place are called mutating. They are fast and convenient, but they can surprise other code that shares the same array (remember references). Since 2023, JavaScript also has non-mutating versions such as toSpliced() and with(), and you'll see when to prefer each kind.

Adding and removing at the ends

Four methods work on the ends of an array. All four mutate it.

Method Does Returns
push(a, b, โ€ฆ) Adds items to the end The new length
pop() Removes the last item The removed item
unshift(a, b, โ€ฆ) Adds items to the start The new length
shift() Removes the first item The removed item
JS push, pop, shift, unshift

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A common slip is expecting push to return the array. It returns the new length, so const list = [].push("x") gives you the number 1.

These methods map onto two classic data structures:

  • A stack (last in, first out), like a pile of plates or an undo history: push to add, pop to take.
  • A queue (first in, first out), like a line at a counter: push to join, shift to serve.

Ends are not equal. push and pop are very fast. shift and unshift must renumber every other item, so they get slower as the array grows. For a few hundred items you won't notice; for huge queues, consider a different structure.

slice(): copy a part

slice(start, end) returns a new array containing the items from start up to, but not including, end. The original is never changed:

JS slice never mutates

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The "up to, but not including" rule means end - start is the number of items you get. Negative values count from the end, just like with at(). slice() with no arguments is a classic way to make a shallow copy.

Strings have a slice() method with the same rules, which you saw in String Methods.

splice(): remove, insert or replace in place

splice() is the all-purpose mutating method. Its signature is splice(start, deleteCount, ...itemsToInsert): go to start, remove deleteCount items, and insert any extra arguments there. It returns an array of the removed items.

JS splice in three ways

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The most common use is removing one item at a known position, for example after finding it:

JavaScript
const index = todos.indexOf("Buy milk");
if (index !== -1) {
  todos.splice(index, 1);
}

The if matters. indexOf() returns -1 when nothing matches, and splice(-1, 1) would happily delete the last item. You'll learn indexOf and its relatives in Searching Arrays.

slice vs splice

The names differ by one letter and the behavior differs completely. A quick way to remember: splice has a "p" for "permanent change".

slice(start, end) splice(start, count, ...items)
Changes the original? No Yes
Second argument End index (excluded) Number of items to remove
Returns The selected items The removed items

concat() and spread: joining arrays

concat() returns a new array made from the original followed by its arguments. Array arguments are flattened one level; other values are added as items:

JavaScript
const morning = ["email", "standup"];
const afternoon = ["review", "deploy"];

const day = morning.concat(afternoon, "wrap-up");
// ["email", "standup", "review", "deploy", "wrap-up"]

Today, spread does the same job and is often clearer: [...morning, ...afternoon, "wrap-up"]. Both leave the inputs unchanged.

join(): array to string

join(separator) glues all items into one string. The default separator is a comma:

JS join

Press Run (or Ctrl + Enter) to see the console output here.

No output.

join pairs naturally with the string method split(): split a string into an array, change the array, join it back.

Non-mutating versions: toSpliced(), with() and friends

Mutation is a problem when an array is shared, for example state in a UI framework, where changing the old array in place means nothing notices the change. ES2023 added copying versions of the mutating methods. They return a new array and leave the original alone:

Mutating Non-mutating copy
splice(...) toSpliced(...)
arr[i] = value with(i, value)
sort() toSorted()
reverse() toReversed()
JS toSpliced and with

Press Run (or Ctrl + Enter) to see the console output here.

No output.

toSpliced() takes the same arguments as splice() but returns the resulting array, not the removed items. with(index, value) is the copying version of assigning to an index; unlike plain assignment, it throws a RangeError for an index outside the array.

These methods are supported in all major browsers since mid-2023 and in Node.js 20+. For older environments, the same results come from spread and slice:

JavaScript
// steps.toSpliced(3, 0, "review")
[...steps.slice(0, 3), "review", ...steps.slice(3)];

// steps.with(1, "prototype")
steps.map((item, i) => (i === 1 ? "prototype" : item));

toSorted() and toReversed() are covered in Sorting Arrays.

Choosing mutating or not

There is no single right answer:

  • Mutate when the array is local to your function, or when you're building it up step by step. push in a loop is perfectly fine.
  • Copy when the array came from somewhere else (a function argument, shared state, a prop) and other code may still be using it.

A good rule: don't mutate data you didn't create, unless that's the function's documented job.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does ["a", "b"].push("c") return?

    push returns the new length of the array, not the array itself.
  2. 2. What is [10, 20, 30, 40].slice(1, 3)?

    slice copies from index 1 up to, but not including, index 3.
  3. 3. After const a = [1, 2, 3, 4]; a.splice(1, 2);, what is a?

    splice(1, 2) removes two items starting at index 1 (2 and 3) from the original array, and returns them.
  4. 4. Why check index !== -1 before list.splice(index, 1)?

    Negative starts count from the end, so a failed search result of -1 would delete the last item.
  5. 5. Which call returns a NEW array with index 2 replaced, leaving the original unchanged?

    with() is the copying version of index assignment. toSpliced(2, 0, โ€ฆ) would insert rather than replace.

Summary

  • push/pop work on the end, unshift/shift on the start; all four mutate, and push/unshift return the new length.
  • slice(start, end) copies a range into a new array and never mutates; end is excluded.
  • splice(start, count, ...items) removes, inserts or replaces in place and returns the removed items.
  • concat() and spread join arrays into a new one; join() turns an array into a string.
  • toSpliced(), with(), toSorted() and toReversed() (ES2023) return modified copies.
  • Mutate arrays you own; copy arrays that other code shares.

Next: map, filter, reduce and forEach โ€” transforming and summarizing arrays.