mutation
Array.prototype.push
Appends one or more elements to the end of the array and returns the new length. Reach for it to grow a list — it's the canonical "add to the end" call.
arr.push(...elements) Parameters
| Parameter | Purpose |
|---|---|
| ...elements | One or more values to append (variadic) |
| return value | The array's new length after pushing |
Examples
const a = [1, 2]; a.push(3); console.log(a); Logs: [1, 2, 3]
const a = [1]; console.log(a.push(2, 3, 4)); Logs: 4 (returns new length, not the array)
const a = [1, 2]; const b = [3, 4]; a.push(...b); console.log(a); Logs: [1, 2, 3, 4] (spread to append another array's contents)
const a = []; a.push([1, 2]); console.log(a); Logs: [[1, 2]] (without spread you get a nested array)
Gotcha
MUTATES the source and returns the new LENGTH, not the array — chaining `.push().map()` will not work. To append an array's contents, spread it (`arr.push(...other)`).
Related methods
Array.prototype.pop
Removes the last element from the array and returns it (or undefined if empty). Reach for it to consume the tail of a list — the natural pair to push for stack behavior.
Array.prototype.unshift
Prepends one or more elements to the front of the array and returns the new length. Reach for it to insert at the head — but be aware every existing item is reindexed.
Array.prototype.concat
Returns a new array formed by joining the source with the provided arrays and/or values (one level of spread). Reach for it to merge arrays without mutating any of them.
Array.prototype.shift
Removes the first element from the array and returns it, reindexing every remaining element. Reach for it to consume the head of a list — the natural queue operation.
Array.prototype.splice
Removes and/or inserts elements at any position in the array, returning the removed items. Reach for it to do insert/delete/replace edits in one call.