If you need to add an item at the beginning of an array in JavaScript, you can use the splice()
method. This method allows you to make modifications to an array by specifying the start index, the delete count, and the items you want to add.
To add an item at the first position of the array, you can follow these steps:
const colors = ['yellow', 'red'];
colors.splice(0, 0, 'blue');
// colors === ['blue', 'yellow', 'red']
In the example above, we have an array called colors
with two elements: ‘yellow’ and ‘red’. By using splice()
, we specify the start index as 0
, the delete count as 0
(since we are not removing any items), and the item we want to add as 'blue'
. The result is that the item ‘blue’ is added at the beginning of the array, and the final array becomes ['blue', 'yellow', 'red']
.
Using the splice()
method with the appropriate arguments allows you to easily add items to the beginning of an array in JavaScript.