How to add items at the beginning of an array in JavaScript

Suppose you want to add an item at the beginning of the array.

To do this, you will usesplice()Array method.

splice()Accept 3 or more parameters. The first is to start indexing: where we will start making changes. The second is to delete the count parameter. YesplusArray, so in all our examples, the delete count is 0. After that, you can add one or more items to add to the array.

To add in the first position, use0As the first parameter:

const colors = ['yellow', 'red']

colors.splice(0, 0, ‘blue’)

//colors === [‘blue’, ‘yellow’, ‘red’]

Download mine for freeJavaScript beginner's manual


More js tutorials: