Arrays
array.push()
Adds items to the end of an array.
Why it exists
Lists in apps keep growing: a new chat message, a new item in the cart, a new entry in the history. You need a way to say "add to the end" without working out what the next index is. push does exactly that. It's also the core of the "collect the result" technique: start with an empty array and drop matching items into it.
Where it's used
- Add a message to a chat or an item to a cart.
- Collect a result in a loop:
result.push(item). - A task queue and an action history (for an "Undo" button).
- Grouping:
groups[key].push(item)— as in the "Group by a property" challenge.
Syntax
array.push(item)Examples
const queue = ["a"];
queue.push("b");
queue.push("c");
queue; // → ["a", "b", "c"]const evens = [];
for (const n of [1, 2, 3, 4]) {
if (n % 2 === 0) evens.push(n);
}
evens; // → [2, 4]const cart = ["tea"];
const newLength = cart.push("coffee", "sugar");
newLength; // → 3
cart; // → ["tea", "coffee", "sugar"]const items = ["tea"];
const next = [...items, "coffee"];
items; // → ["tea"]
next; // → ["tea", "coffee"]...Results after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
push writes the value at index length and increases length by 1. You can pass several values at once: arr.push(1, 2, 3).
push changes the array itself ("mutates" it) and returns the new length, not the array. So const b = a.push(x) is a common mistake: b ends up holding a number.
Since the array changes in place, every variable that points to that array sees the change. In React state you mustn't do this — you create a new array instead: [...items, newItem].
Its partner pop removes the last item, while unshift/shift work with the start of the array (but are slower on big arrays — every index has to shift).
Traps
How it differs from…
array.map()If each item becomes exactly one new item, map is shorter than a loop with
push.pushis for when the result may have fewer or more items.array.filter()A loop with a condition and
pushis what filter does for you in one line.
When to pick something else
Practice
Lessons where this appears
- Byte's sock empireTale · Chapter 5 · Arrays and loops
- The Infinite LoopBoss · Chapter 5 · Arrays and loops
- Why can't you fix a string?Why? · Chapter 6 · Strings
- The RepackerBoss · Chapter 9 · Destructuring, spread and rest
- Why map and not a loop?Why? · Chapter 10 · map, filter, reduce
- How a shop is builtTale · Chapter 17 · Project: an online shop