It is the first array method anyone learns, and often the last one anyone questions. Filling a list inside a loop, stacking up results, adding a line to a cart: push is everywhere.
Two details still deserve attention: what it hands back, and the fact that it changes the existing array.
Definition
push adds one or more items to the end of an Array and hands back the new length of that array, never the array itself.
const guests = ["Alice"];
const size = guests.push("Bob", "Chloe");
console.log(size); // 3, the new length
console.log(guests); // [ 'Alice', 'Bob', 'Chloe' ]
const others = ["Diane", "Emile"];
guests.push(...others);
console.log(guests.length); // 5That last line uses Spread (...) to hand over each item separately. Without it, push(others) would add a single item that happens to be an array, and the length would go to 4.
The family of four
| Method | What it does | What it hands back |
|---|---|---|
push(x) | Adds at the end | The new length |
pop() | Removes the last one | The removed item |
unshift(x) | Adds at the start | The new length |
shift() | Removes the first one | The removed item |
The three columns give the name, the effect and the return value. All four methods change the array in place: the ones that add hand back a number, the ones that remove hand back the item, and pop on an empty array hands back undefined without raising an error.
push or a copy
The [...list, item] form builds a new array instead of changing the existing one. It costs more, and it is still what belongs in an interface state, where only a new reference triggers a redraw.
const list = [1];
const copy = [...list, 2];
list.push(3);
console.log(list); // [ 1, 3 ]
console.log(copy); // [ 1, 2 ], the copy did not followThe other way around, inside a loop building a local result, push remains the right call. Copying the array on every turn turns work proportional to the number of items into work proportional to its square, which shows up from a few thousand rows on.
Frequently asked questions
Why does const updated = list.push(x) not give an array?
Because push hands back the new length, a number. The variable therefore holds 3 rather than the expected list, and the error shows up later, as a message saying some array method does not exist on a number. The changed array is the starting variable.
Can you push onto an array declared with const?
Yes, and it often comes as a surprise. const forbids reassigning the variable, not changing the value it points at. Adding, removing or sorting stays allowed; only list = [] raises an error.
Can everything be concatenated with push(...otherArray)?
At everyday sizes, yes, and it is faster than concat since nothing is copied. Past a few hundred thousand items, each value becoming an argument, the call stack fills up and a RangeError appears. A loop or concat then take over.