JavaScript Array Push Tutorial
Jul 9, 2019
In JavaScript, the Array#push()
method adds its arguments to the end of the array. It returns the new length of the array after the elements are added.
const arr = ['A', 'B', 'C'];
arr.push('D'); // 4
arr; // ['A', 'B', 'C', 'D']
arr.push('E', 'F'); // 6
arr; // ['A', 'B', 'C', 'D', 'E', 'F']
Using the Spread Operator
Suppose you want to add all the elements from another array arr2
to the end of
arr
. Doing arr.push(arr2)
will not add the elements from arr2
, it will
instead add the array arr2
as an element.
const arr = ['A', 'B', 'C'];
const arr2 = ['D', 'E'];
arr.push(arr2); // 4
arr; // ['A', 'B', 'C', ['D', 'E']]
To add the elements of arr2
to the end of arr
, use the spread operator. You can
think of ...
as converting the array into positional arguments.
const arr = ['A', 'B', 'C'];
const arr2 = ['D', 'E'];
// Equivalent to `arr.push('D', 'E')`
arr.push(...arr2); // 5
arr; // ['A', 'B', 'C', 'D', 'E']
More Fundamentals Tutorials
- How to Add 2 Arrays Together in JavaScript
- The String `match()` Function in JavaScript
- Convert a Set to an Array in JavaScript
- What Does Setting the Length of a JavaScript Array Do?
- Get the Last Element in an Array in JavaScript
- Skip an Index in JavaScript Array map()
- Conditionally Add an Object to an Array in JavaScript