Add an item at the beginning of an array in JavaScript
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.
Checkout more articles on JavaScript
Ways to add an item at the beginning of an array
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.
1 2 3 4 5 6 7 | var colours=["Black"]; colours.unshift("Blue"); // Output: ["Blue","Black"] colours.unshift("Yellow","Orange"); // Output: ["Yellow","Orange","Blue","Black"] |
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.
1 2 3 4 | 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.
1 2 3 4 | let arr1 = ['A', 'B', 'C']; let arr2 = ['A0'].concat(arr1); console.log(arr2); // Output: ['A0', 'A', 'B', 'C'] |
That’s it for today.
Thank you for reading. Happy Coding..!! 🙂