Add an item to an array in JavaScript
📅February 28, 2023
Today we will show you how to add an item at the beginning of an array in JavaScript. In this article, we will show you three different ways to prepend items to an array.
Ways to add an item at the beginning of an array
- Using unshift() method
- Using spread operator
- Using concat() method
- Using push() method
- Using splice() method
1. Using unshift() method
The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.
var colours=["Black"];
colours.unshift("Blue");
// Output: ["Blue","Black"]
colours.unshift("Yellow","Orange");
// Output: ["Yellow","Orange","Blue","Black"]
2. Using spread operator
We can achieve the same thing using the Spread Operator.
let arr1 = ['A', 'B', 'C'];
let arr2 = ['A0', ...arr1];
console.log(arr2);
// Output: ['A0', 'A', 'B', 'C']
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 = ['A0'].concat(arr1);
console.log(arr2);
// Output: ['A0', 'A', 'B', 'C']
4. Using push() method
The push()
method adds one or more items to the end of an array.
const fruits = ["apple", "banana"];
fruits.push("orange", "mango");
console.log(fruits);
// Output: ["apple", "banana", "orange", "mango"]
5. Using splice() method
The splice()
method can be used to add new items at a specific index in an array.
const arr = ["a", "b", "c"];
arr.splice(1, 0, "d");
console.log(arr);
// Output: ["a", "d", "b", "c"]
That’s it for today.
Thank you for reading. Happy Coding..!! 🙂