Adding and Removing Array Items
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(...)andwith(index, value)(ES2023) change a copy. - Changing methods return different things:
pushreturns the new length, not the array.
Method Table
| Method | Changes the array? | Returns | Description |
|---|---|---|---|
push(...items) | Yes | New length | It is used to add items to the end. |
pop() | Yes | Removed item | It is used to remove the last item. |
unshift(...items) | Yes | New length | It is used to add items to the start. |
shift() | Yes | Removed item | It is used to remove the first item. |
splice(start, count, ...items) | Yes | Array of removed items | It is used to remove, insert or replace items anywhere. |
fill(value, start, end) | Yes | The array | It is used to set a range to one value. |
copyWithin(target, start, end) | Yes | The array | It is used to copy a range inside the array (rare). |
slice(start, end) | No | New array | It is used to copy part of an array. |
concat(...arrays) | No | New array | It is used to join arrays and values. |
toSpliced(start, count, ...items) | No | New array | It is used to get a spliced copy (ES2023). |
with(index, value) | No | New array | It is used to get a copy with one item replaced (ES2023). |
Adding and Removing at the Ends
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());['Navika', 'Srihitha', 'Advitha'] 3
Advitha ['Navika', 'Srihitha']
['Advitha', 'Navika', 'Srihitha']
Advitha ['Navika', 'Srihitha']
undefinedExplanation: 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
array.splice(start, deleteCount, item1, item2, ...)Example
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);['books', 'lab'] ['tuition', 'uniform']
['tuition', 'bus', 'lunch', 'uniform']
['tuition', 'bus', 'lunch', 'sports']
['tuition', 'bus']| Call | Effect |
|---|---|
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:
const students = ["Navika", "Srihitha", "Advitha"];
const index = students.indexOf("Srihitha");
if (index !== -1) students.splice(index, 1);
console.log(students);['Navika', 'Advitha']Always check for -1 first: splice(-1, 1) would remove the last item instead.
Copies: slice and concat
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]);[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:
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);['tuition', 'lab']
['tuition', 'bus', 'books', 'lab']
['tuition', 'books', 'science lab']
['tuition', 'books', 'lab']| Changes in place | Returns a changed copy |
|---|---|
splice | toSpliced |
arr[i] = v | with(i, v) |
sort | toSorted (sorting lesson) |
reverse | toReversed (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:
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);['Srihitha $90', 'Advitha $45']
2 3 90 2Every 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
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);['Advitha', 'Navika', 'Srihitha']
['Srihitha', 'Advitha', 'Navika']
['Navika', 'Srihitha', 'Advitha']Key Takeaways
| Goal | In place | New array |
|---|---|---|
| Add to end | a.push(x) | [...a, x] |
| Add to start | a.unshift(x) | [x, ...a] |
| Remove at index | a.splice(i, 1) | a.toSpliced(i, 1) |
| Replace at index | a[i] = x | a.with(i, x) |
| Part of the array | n/a | a.slice(start, end) |
Was this tutorial helpful?