How to add items to an array in JavaScript

In vanilla JavaScript, you can use the Array.push() method to add new items to an array. This method appends one or more items at the end of the array and returns the new length.

Here is an example:

const fruits = ['Orange', 'Mango', 'Banana'];

// add more fruits
fruits.push('Apple', 'Lemon');

console.log(fruits);

// ['Orange', 'Mango', 'Banana', 'Apple', 'Lemon']

If you want to append items to the beginning of an array, use the Array.unshift() method instead. This method works similar to Array.push() except that the given items are added at the start of the array:

const fruits = ['Orange', 'Mango', 'Banana'];

// add more fruits
fruits.unshift('Kiwi', 'Lemon');

console.log(fruits);

// ['Kiwi', 'Lemon', 'Orange', 'Mango', 'Banana']

Adding item at a specific index

To add a new item at a particular index in an array, you can use the Array.splice() method. This method adds new items at the specified starting index and returns the removed items if any.

Here is an example that demonstrates how to add a new item at 3rd index in an array using Array.splice():

const fruits = ['Apple', 'Orange', 'Mango', 'Banana'];

const removed = fruits.splice(2, 0, 'Cherry');

console.log(fruits); // ['Apple', 'Orange', 'Cherry', 'Mango', 'Banana']
console.log(removed); // []

Merging two arrays

What if you want to add all items of an array to another array? You can use the Array.concat() method to merge two or more arrays together. This method takes one or more arrays as input and merges all subsequent arrays into the first:

const fruits = ['Orange', 'Mango', 'Banana'];

const moreFruits = ['Kiwi', 'Lemon'];

// merge all fruits
const allFruits = fruits.concat(moreFruits);

console.log(allFruits);

// ['Orange', 'Mango', 'Banana', 'Kiwi', 'Lemon']

The Array.concat() method doesn't change the original arrays. Instead, it always returns a new array.

Take a look at this article to learn more about JavaScript arrays and how to use them to store multiple pieces of information in one single variable.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.