How to append an item to an array in JavaScript

By

Learn the ways to append an item to an array in JavaScript: use push() to mutate the original array, or concat() to return a new array with the items added.

~~~

To append an item to an array in JavaScript, call the push() method on the array. If you’d rather leave the original array untouched, use concat() or the spread operator, which give you a new array instead. Let’s see all the options.

Append a single item

To append a single item to an array, use the push() method provided by the Array object:

const fruits = ['banana', 'pear', 'apple']
fruits.push('mango')

push() mutates the original array. After this call, fruits contains 4 items.

To create a new array instead, use the concat() Array method:

const fruits = ['banana', 'pear', 'apple']
const allfruits = fruits.concat('mango')

Notice that concat() does not actually add an item to the array, but creates a new array, which you can assign to another variable, or reassign to the original array (declaring it as let, as you cannot reassign a const):

let fruits = ['banana', 'pear', 'apple']
fruits = fruits.concat('mango')

You can get the same result with the spread operator:

const fruits = ['banana', 'pear', 'apple']
const allfruits = [...fruits, 'mango']

Here too, the original fruits array is left untouched.

Append multiple items

To append multiple items to an array, you can use push() by calling it with multiple arguments:

const fruits = ['banana', 'pear', 'apple']
fruits.push('mango', 'melon', 'avocado')

You can also use the concat() method you saw before, passing a list of items separated by a comma:

const fruits = ['banana', 'pear', 'apple']
const allfruits = fruits.concat('mango', 'melon', 'avocado')

or an array:

const fruits = ['banana', 'pear', 'apple']
const allfruits = fruits.concat(['mango', 'melon', 'avocado'])

Remember that as described previously this method does not mutate the original array, but it returns a new array.

When you pass an array to concat(), its items are spread one level deep. If one of those items is itself an array, it stays nested. Keep that in mind when appending arrays of arrays.

Watch out for the return value of push()

A common mistake is assigning the result of push() to a variable:

const fruits = ['banana', 'pear', 'apple']
const result = fruits.push('mango')

console.log(result) // 4

push() does not return the array. It returns the new length of the array. The updated array is still fruits.

concat() and the spread operator are the ones that give you back an array. Pick push() when mutating is fine, and one of the other two when you want to keep the original data intact.

~~~

Related posts about js: