Add an item to an array in JavaScript
📅January 14, 2022
Today we will show you how to add an item to an array in JavaScript. In this article, we will show you three different ways to add items to the end of an array.
In a previous article, we explained how to add an item at the beginning of an array in JavaScript.
Checkout more articles on JavaScript
- Scroll to a specific element using JavaScript
- How to insert an element after another element in JavaScript
- How to get the web page size in JavaScript
- Methods of Promises in JavaScript
Ways to add an item to an array
1. Using unshift() method
The push() method adds one or more elements to the end of an array and returns the new length of the array.
var colours=["Black"];
colours.push("Blue");
// Output: ["Black","Blue"]
colours.push("Yellow","Orange");
// Output: ["Black","Blue","Yellow","Orange"]
You may like this article: Push, Pop, Shift and Unshift Array Methods in JavaScript
2. Using spread operator
We can achieve the same thing using the Spread Operator.
let arr1 = ['A', 'B', 'C'];
let arr2 = [...arr1, 'D'];
console.log(arr2);
// Output: ['A', 'B', 'C', 'D']
3. Using concat() method
The concat() method is used to merge two or more arrays. This method does not change the existing arrays but instead returns a new array.
let arr1 = ['A', 'B', 'C'];
let arr2 = arr1.concat(['D']);
console.log(arr2);
// Output: ['A', 'B', 'C', 'D']
That’s it for today.
Thank you for reading. Happy Coding..!! 🙂