File size: 5,528 Bytes
780c9fe |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 |
---
title: Array.prototype.push()
short-title: push()
slug: Web/JavaScript/Reference/Global_Objects/Array/push
page-type: javascript-instance-method
browser-compat: javascript.builtins.Array.push
sidebar: jsref
---
The **`push()`** method of {{jsxref("Array")}} instances adds the specified elements to the end of
an array and returns the new length of the array.
{{InteractiveExample("JavaScript Demo: Array.prototype.push()")}}
```js interactive-example
const animals = ["pigs", "goats", "sheep"];
const count = animals.push("cows");
console.log(count);
// Expected output: 4
console.log(animals);
// Expected output: Array ["pigs", "goats", "sheep", "cows"]
animals.push("chickens", "cats", "dogs");
console.log(animals);
// Expected output: Array ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]
```
## Syntax
```js-nolint
push()
push(element1)
push(element1, element2)
push(element1, element2, /* …, */ elementN)
```
### Parameters
- `element1`, …, `elementN`
- : The element(s) to add to the end of the array.
### Return value
The new {{jsxref("Array/length", "length")}} property of the object upon which the method was called.
## Description
The `push()` method appends values to an array.
{{jsxref("Array.prototype.unshift()")}} has similar behavior to `push()`, but applied to the start of an array.
The `push()` method is a [mutating method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#copying_methods_and_mutating_methods). It changes the length and the content of `this`. In case you want the value of `this` to be the same, but return a new array with elements appended to the end, you can use [`arr.concat([element0, element1, /* ... ,*/ elementN])`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat) instead. Notice that the elements are wrapped in an extra array — otherwise, if the element is an array itself, it would be spread instead of pushed as a single element due to the behavior of `concat()`.
The `push()` method is [generic](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable.
## Examples
### Adding elements to an array
The following code creates the `sports` array containing two elements, then
appends two elements to it. The `total` variable contains the new length of
the array.
```js
const sports = ["soccer", "baseball"];
const total = sports.push("football", "swimming");
console.log(sports); // ['soccer', 'baseball', 'football', 'swimming']
console.log(total); // 4
```
### Merging two arrays
This example uses {{jsxref("Operators/Spread_syntax", "spread syntax", "", 1)}} to push all elements from a
second array into the first one.
```js
const vegetables = ["parsnip", "potato"];
const moreVegs = ["celery", "beetroot"];
// Merge the second array into the first one
vegetables.push(...moreVegs);
console.log(vegetables); // ['parsnip', 'potato', 'celery', 'beetroot']
```
Merging two arrays can also be done with the {{jsxref("Array/concat", "concat()")}} method.
### Calling push() on non-array objects
The `push()` method reads the `length` property of `this`. It then sets each index of `this` starting at `length` with the arguments passed to `push()`. Finally, it sets the `length` to the previous length plus the number of pushed elements.
```js
const arrayLike = {
length: 3,
unrelated: "foo",
2: 4,
};
Array.prototype.push.call(arrayLike, 1, 2);
console.log(arrayLike);
// { '2': 4, '3': 1, '4': 2, length: 5, unrelated: 'foo' }
const plainObj = {};
// There's no length property, so the length is 0
Array.prototype.push.call(plainObj, 1, 2);
console.log(plainObj);
// { '0': 1, '1': 2, length: 2 }
```
### Using an object in an array-like fashion
As mentioned above, `push` is intentionally generic, and we can use that to
our advantage. `Array.prototype.push` can work on an object just fine, as
this example shows.
Note that we don't create an array to store a collection of objects. Instead, we store
the collection on the object itself and use `call` on
`Array.prototype.push` to trick the method into thinking we are dealing with
an array—and it just works, thanks to the way JavaScript allows us to establish the
execution context in any way we want.
```js
const obj = {
length: 0,
addElem(elem) {
// obj.length is automatically incremented
// every time an element is added.
[].push.call(this, elem);
},
};
// Let's add some empty objects just to illustrate.
obj.addElem({});
obj.addElem({});
console.log(obj.length); // 2
```
Note that although `obj` is not an array, the method `push`
successfully incremented `obj`'s `length` property just like if we
were dealing with an actual array.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Array.prototype.push` in `core-js` with fixes of this method](https://github.com/zloirock/core-js#ecmascript-array)
- [es-shims polyfill of `Array.prototype.push`](https://www.npmjs.com/package/array.prototype.push)
- [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide
- {{jsxref("Array")}}
- {{jsxref("Array.prototype.pop()")}}
- {{jsxref("Array.prototype.shift()")}}
- {{jsxref("Array.prototype.unshift()")}}
- {{jsxref("Array.prototype.concat()")}}
- {{jsxref("Array.prototype.splice()")}}
|