Array.prototype.push()
The workhorse for building an array. Two things catch people: it returns a number rather than the array, so it cannot be chained, and it mutates.
Demo
Every output here is a NUMBER — the new length after the append, which is what push returns. Pushing onto a three-element array gives 4, not [1, 2, 3, 4]. That is the single most surprising thing about the method, and the reason `const arr = old.push(x)` leaves you holding an integer instead of an array.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| ...items | any | no (none) | Any number of values, appended in order. Each is added as ONE element, even if it is itself an array. |
Return value
number — The NEW length of the array — not the array, and not the pushed element. The array is modified in place.
Common patterns
const out = []; for (const x of input) out.push(transform(x));
items.push(...more);
const next = [...items, value];
Examples
Pitfalls
const next = items.push(value);
items.push(value); const next = items;
const a = [1]; a.push([2, 3]); a
a.push(...[2, 3]);
state.items.push(x);
setItems([...state.items, x]);
out.push(...hugeArray);
for (const x of hugeArray) out.push(x);
When to use
- Building an array incrementally in a loop
- Appending to an array you own
- Stack behaviour, paired with pop
- The array is shared or state → [...items, value]
- You want the array back for chaining → concat or a spread
- Adding to the FRONT → unshift, though it is O(n)
Notes
FAQ
It returns the new length, which dates back to ES3 and is occasionally useful for bookkeeping. It does mean push cannot be chained, and that assigning its result gives you an integer rather than the array you probably wanted.
const len = items.push(x); // a number