How to append items to an array in JavaScript

Find out the way JavaScript provides you to append items to the array and the canonical way you should use

Attach a single item

To append a single item to the array, usepush()The methods provided by the Array object:

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

push()Change the original array.

To create a new array, useconcat()Array method:

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

noteconcat()No items are actually added to the array, but a new array is created, which you can assign to another variable, or reassign to the original array (declare it asletBecause you cannot reassignconst):

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

Append multiple items

To append multiple items to the array, you can usepush()Call it by using multiple parameters:

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

You can also useconcat()The method you saw earlier, passing a comma-separated list of items:

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

Or array:

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

Remember, as mentioned earlier, this method will not mutate the original array, but will return a new array.

Download mine for freeJavaScript beginner's manual


More js tutorials: