How to add items to the start of an array in JavaScript
To add an item to the beginning of an array in JavaScript, you can use the unshift()
method. The unshift()
method adds one or more elements to the start of an array and returns the new length of the array.
Here’s an example of adding an item to the beginning of an array:
1 2 3 | const myArray = ["item1", "item2", "item3"]; myArray.unshift("newItem"); console.log(myArray); // ["newItem", "item1", "item2", "item3"] |
In this example, we first declare an array myArray
with three elements. We then use the unshift()
method to add the string "newItem"
to the beginning of the array. The console output will show that "newItem"
is now the first element of the array.
You can also add multiple items to the beginning of an array by passing them as separate arguments to the unshift()
method:
1 2 3 | const myArray = ["item1", "item2", "item3"]; myArray.unshift("newItem1", "newItem2", "newItem3"); console.log(myArray); // ["newItem1", "newItem2", "newItem3", "item1", "item2", "item3"] |
In this example, we pass three strings as arguments to the unshift()
method, and they are all added to the beginning of the array. The console output will show that the new items are now the first three elements of the array.
I hope you find this article helpful.
Thank you for reading. Happy Coding..!!