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']

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Fundamentals Tutorials