Discover the different ways JavaScript provides for appending an item to an array and learn about the recommended approach.
Appending a Single Item
In order to append a single item to an array, you can make use of the push()
method offered by the Array object. Here’s an example:
const fruits = ['banana', 'pear', 'apple'];
fruits.push('mango');
It’s important to note that push()
modifies the original array.
If you want to create a new array instead of modifying the original one, you can employ the concat()
method of the Array object. This is demonstrated below:
const fruits = ['banana', 'pear', 'apple'];
const allFruits = fruits.concat('mango');
Observe that concat()
does not directly add an item to the original array. Instead, it creates a new array. You can assign the new array to another variable or reassign it to the original array. Please note that you need to use let
to declare the array as const
does not allow reassignment:
let fruits = ['banana', 'pear', 'apple'];
fruits = fruits.concat('mango');
Appending Multiple Items
To append multiple items to an array, you can utilize the push()
method by passing multiple arguments to it. Here’s an example:
const fruits = ['banana', 'pear', 'apple'];
fruits.push('mango', 'melon', 'avocado');
Alternatively, you can employ the concat()
method, as shown earlier, by separating the items with commas:
const fruits = ['banana', 'pear', 'apple'];
const allFruits = fruits.concat('mango', 'melon', 'avocado');
You can also pass an array as an argument to the concat()
method:
const fruits = ['banana', 'pear', 'apple'];
const allFruits = fruits.concat(['mango', 'melon', 'avocado']);
Remember that, similar to the previous method, concat()
does not modify the original array, but returns a new one.