Summary
Mutates an array by appending the given elements and returning the new length of the array.
Method of Array |
|
|---|---|
| Implemented in | JavaScript 1.2 |
| ECMAScript Edition | ECMAScript 3rd Edition |
Syntax
array.push(element1, ..., elementN)
Parameters
-
element1, ..., elementN - The elements to add to the end of the array.
Returns
The new length property of the object upon which the method was called.
Description
The push method is useful for easily appending values to an array.
push is intentionally generic. This method can be called or applied to objects resembling arrays. The push method relies on a length property to determine where to start inserting the given values. If the length property cannot be converted into a number, the index used is 0. This includes the possibility of length being nonexistent, in which case length will also be created.
The only native, array-like objects are strings, although they are not suitable in applications of this method, as strings are immutable.
Examples
Example: Adding elements to an array
The following code creates the sports array containing two elements, then appends two elements to it. After the code executes, sports contains 4 elements: "soccer", "baseball", "football" and "swimming".
var sports = ["soccer", "baseball"];
sports.push("football", "swimming");
Mozilla Developer Network