Adding and Removing Array Items

Updated · 7 min read
mediumES2026javascriptarrayspushspliceslice

Arrays change constantly: a payment is added, a canceled one is removed, a correction replaces an entry. JavaScript has methods that change the array in place (push, pop, shift, unshift, splice) and methods that return a new array and leave the original alone (slice, concat, toSpliced, with). Knowing which is which is the difference between a clean update and a bug where data changes behind your back.

In One Minute

  • At the end: push(items) adds, pop() removes and returns the last item.
  • At the start: unshift(items) adds, shift() removes and returns the first item.
  • Anywhere: splice(start, deleteCount, ...items) removes and/or inserts in place, returning the removed items.
  • Copies: slice(start, end) extracts, concat(...) joins, toSpliced(...) and with(index, value) (ES2023) change a copy.
  • Changing methods return different things: push returns the new length, not the array.

Method Table

MethodChanges the array?ReturnsDescription
push(...items)YesNew lengthIt is used to add items to the end.
pop()YesRemoved itemIt is used to remove the last item.
unshift(...items)YesNew lengthIt is used to add items to the start.
shift()YesRemoved itemIt is used to remove the first item.
splice(start, count, ...items)YesArray of removed itemsIt is used to remove, insert or replace items anywhere.
fill(value, start, end)YesThe arrayIt is used to set a range to one value.
copyWithin(target, start, end)YesThe arrayIt is used to copy a range inside the array (rare).
slice(start, end)NoNew arrayIt is used to copy part of an array.
concat(...arrays)NoNew arrayIt is used to join arrays and values.
toSpliced(start, count, ...items)NoNew arrayIt is used to get a spliced copy (ES2023).
with(index, value)NoNew arrayIt is used to get a copy with one item replaced (ES2023).

Adding and Removing at the Ends

ends.js▶ Try it
const queue = ["Navika", "Srihitha"];
 
const newLength = queue.push("Advitha");
console.log(queue, newLength);
 
const last = queue.pop();
console.log(last, queue);
 
queue.unshift("Advitha");
console.log(queue);
 
const first = queue.shift();
console.log(first, queue);
 
console.log([].pop());
Output
['Navika', 'Srihitha', 'Advitha'] 3
Advitha ['Navika', 'Srihitha']
['Advitha', 'Navika', 'Srihitha']
Advitha ['Navika', 'Srihitha']
undefined

Explanation: push and unshift return the new length, while pop and shift return the removed item. On an empty array, pop and shift return undefined instead of throwing.

push and pop together make a stack (last in, first out), like the undo history in an editor. push and shift together make a queue (first in, first out), like students waiting in line.

splice: Changing the Middle

splice is the all-purpose method for changing an array in place. It removes deleteCount items starting at start, inserts any extra arguments there, and returns an array of what it removed.

Syntax

syntax.js
array.splice(start, deleteCount, item1, item2, ...)

Example

splice.js▶ Try it
const items = ["tuition", "books", "lab", "uniform"];
 
const removed = items.splice(1, 2);
console.log(removed, items);
 
items.splice(1, 0, "bus", "lunch");
console.log(items);
 
items.splice(-1, 1, "sports");
console.log(items);
 
items.splice(2);
console.log(items);
Output
['books', 'lab'] ['tuition', 'uniform']
['tuition', 'bus', 'lunch', 'uniform']
['tuition', 'bus', 'lunch', 'sports']
['tuition', 'bus']
CallEffect
splice(1, 2)Remove 2 items starting at index 1
splice(1, 0, a, b)Insert a and b at index 1, removing nothing
splice(-1, 1, x)Replace the last item with x
splice(2)Remove everything from index 2 to the end

Removing an Item by Value

splice works by position, so find the index first:

remove-value.js▶ Try it
const students = ["Navika", "Srihitha", "Advitha"];
const index = students.indexOf("Srihitha");
if (index !== -1) students.splice(index, 1);
console.log(students);
Output
['Navika', 'Advitha']

Always check for -1 first: splice(-1, 1) would remove the last item instead.

Copies: slice and concat

copies.js▶ Try it
const fees = [120, 85, 45, 200];
 
console.log(fees.slice(1, 3));
console.log(fees.slice(-2));
const copy = fees.slice();
copy.push(999);
console.log(fees, copy.length);
 
const fall = [120, 85];
const spring = [45, 200];
console.log(fall.concat(spring, [10], 5));
console.log([...fall, ...spring]);
Output
[85, 45]
[45, 200]
[120, 85, 45, 200] 5
[120, 85, 45, 200, 10, 5]
[120, 85, 45, 200]

slice(start, end) copies from start up to (not including) end, with negative values counting from the end. slice() with no arguments copies the whole array. concat joins arrays and loose values into a new array; spread syntax ([...a, ...b]) does the same and is more common in modern code.

Change a Copy: toSpliced and with (ES2023)

Modern code, especially user interface code, prefers not to change data in place, because shared arrays changing unexpectedly cause hard-to-find bugs. ES2023 added non-mutating versions of the changing methods:

non-mutating.js▶ Try it
const items = ["tuition", "books", "lab"];
 
const withoutBooks = items.toSpliced(1, 1);
const withBus = items.toSpliced(1, 0, "bus");
const fixed = items.with(2, "science lab");
 
console.log(withoutBooks);
console.log(withBus);
console.log(fixed);
console.log(items);
Output
['tuition', 'lab']
['tuition', 'bus', 'books', 'lab']
['tuition', 'books', 'science lab']
['tuition', 'books', 'lab']
Changes in placeReturns a changed copy
splicetoSpliced
arr[i] = vwith(i, v)
sorttoSorted (sorting lesson)
reversetoReversed (sorting lesson)

In Practice

The Fee Tracker's payment list supports adding, canceling and correcting payments without changing the original list, so an "undo" can return to the previous version:

payments.js▶ Try it
const v1 = [
  { id: 1, name: "Navika", amount: 120 },
  { id: 2, name: "Srihitha", amount: 85 },
];
 
const addPayment = (list, payment) => [...list, payment];
const cancelPayment = (list, id) => list.toSpliced(list.findIndex((p) => p.id === id), 1);
const correctAmount = (list, id, amount) => {
  const i = list.findIndex((p) => p.id === id);
  return list.with(i, { ...list[i], amount });
};
 
const v2 = addPayment(v1, { id: 3, name: "Advitha", amount: 45 });
const v3 = correctAmount(v2, 2, 90);
const v4 = cancelPayment(v3, 1);
 
console.log(v4.map((p) => `${p.name} $${p.amount}`));
console.log(v1.length, v2.length, v3[1].amount, v4.length);
Output
['Srihitha $90', 'Advitha $45']
2 3 90 2

Every version is still intact, so undo is just "go back to the previous variable". (In production, check that findIndex didn't return -1 before using the index.)

Common Mistakes

Using push's return value as the array. const list = old.push(x) stores a number. Use [...old, x] for a new array, or call push on its own line.

Confusing slice and splice. One copies, one changes.

splice with an index of -1 from a failed indexOf. It removes the last item. Check the index first.

Removing items while looping forward. Indexes shift and items are skipped. Loop backward, or build a new array with filter.

Practice

Challenge: Write moveItem(list, from, to) that returns a new array with the item at index from moved to index to, leaving list unchanged.

Show solution
move.js▶ Try it
function moveItem(list, from, to) {
  const item = list[from];
  return list.toSpliced(from, 1).toSpliced(to, 0, item);
}
 
const order = ["Navika", "Srihitha", "Advitha"];
console.log(moveItem(order, 2, 0));
console.log(moveItem(order, 0, 2));
console.log(order);
Output
['Advitha', 'Navika', 'Srihitha']
['Srihitha', 'Advitha', 'Navika']
['Navika', 'Srihitha', 'Advitha']

Quick check: Adding and removing

3 questions
1What does [1, 2].push(3) return?
2Which method changes the original array?
3What does ["a", "b", "c"].with(1, "x") return?

Key Takeaways

GoalIn placeNew array
Add to enda.push(x)[...a, x]
Add to starta.unshift(x)[x, ...a]
Remove at indexa.splice(i, 1)a.toSpliced(i, 1)
Replace at indexa[i] = xa.with(i, x)
Part of the arrayn/aa.slice(start, end)

Was this tutorial helpful?

Lesson 32 of 139