JavaScript Reference ยท Array
Array.prototype.push()
Reference for JavaScript Array.prototype.push(): append one or more elements, the new length it returns, spreading arrays into it and avoiding mutation.
The push() method adds one or more elements to the end of an array and returns the array's new length. It changes the array in place.
It is the standard way to build a list while looping, and, with pop(), to use an array as a stack.
const list = [1, 2]; list.push(3, 4); // returns 4 // list is now [1, 2, 3, 4]
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
array.push() array.push(element1) array.push(element1, element2, /* ..., */ elementN)
| Name | Description |
|---|---|
element1, ..., elementN |
The values to append, in order. Each one becomes a single element, even if it is an array. |
Return value: the new length of the array.
Exceptions: a TypeError if the array is frozen or not extensible, or if the new length would exceed the maximum array length.
Usage notes
- It mutates. If other code holds a reference to the same array, it sees the new items. For an immutable update in state-driven code, create a new array with
[...old, item]orold.concat(item). - The return value is the length, not the array. Chaining
arr.push(1).push(2)fails because a number has nopush. Call it twice, or pass both values at once. - Arrays are not flattened.
a.push([3, 4])adds one element that is an array. To append the items individually, spread them:a.push(...b). - Spreading very large arrays into
push()can exceed the engine's argument limit. For huge lists, loop, or useconcat()to build a new array. - Appending to the end is cheap. Engines optimize it well, so
push()in a loop is fine. - Assigning past the end (
arr[arr.length] = x) does the same for one item, butpush()states the intent. - Generic. It works on array-likes with
Array.prototype.push.call(obj, x); it setslengthon the object. - Add to the start with
unshift(), and insert in the middle withsplice().
Browser support
Array.prototype.push() is part of ES3 and works everywhere.